Databases 4 min read

Does SELECT FOR UPDATE Lock Rows or the Whole Table in MySQL?

This article explains how MySQL's SELECT … FOR UPDATE adds a pessimistic lock, and demonstrates that using an indexed column or primary key results in a row lock, while lacking an index causes a table lock, with step‑by‑step verification using multiple transaction examples.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Does SELECT FOR UPDATE Lock Rows or the Whole Table in MySQL?

Select queries normally do not acquire locks, but using SELECT ... FOR UPDATE adds a pessimistic lock.

The lock type depends on whether the query uses an indexed column or primary key: with an index/PK it locks rows; without it locks the entire table.

To verify, disable autocommit ( set @@autocommit=0;) and run several test cases.

Test case 1

Transaction A selects a row by primary key id=1 and holds the lock; Transaction B attempts to update the same row and is blocked, showing a row lock.

Test case 2

Another transaction updates a different row (id=2) while the first transaction holds a lock, illustrating lock behavior.

Test case 3 (with index)

The table is created with a unique index on the age column; subsequent queries using this indexed column acquire row locks.

Test case 4 (no index)

Using a non‑indexed column code for the query results in a table lock.

Result

If the query condition uses an index or primary key, SELECT ... FOR UPDATE performs a row lock; otherwise it locks the whole table.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

mysqlrow locktable lockSELECT FOR UPDATE
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.