MySQL Locking: Row, Gap and Next-Key Locks, FOR UPDATE and SKIP LOCKED

MySQL 65 min min read Updated: Nov 27, 2026 Advanced
MySQL Locking: Row, Gap and Next-Key Locks, FOR UPDATE and SKIP LOCKED
Advanced Topic 2 of 3

Row Locks

InnoDB locks rows (strictly, index records), not whole tables, for normal changes. UPDATE and DELETE take an exclusive lock on the rows they change, and the lock lasts until the transaction ends.

Writers Block Writers

Session A updates Asha's row without committing. Session B tries to update the same row and waits. After A commits, B continues from the new value, so no update is lost. This is real output of two connections:

text A START TRANSACTION A UPDATE accounts SET balance = balance - 30 WHERE id = 1 A (B has been waiting about 2 seconds) A COMMIT B UPDATE accounts SET balance = balance + 5 WHERE id = 1 B waited at least 2 seconds: True A SELECT balance FROM accounts WHERE id = 1 -> [[75]]

Asha: 100 - 30 + 5 = 75, correct.

Lock Wait Timeout

B does not wait forever. After innodb_lock_wait_timeout seconds (50 by default) MySQL gives up with error 1205. This test set it to 2 seconds. Only the statement fails; the transaction stays open, so the application should roll back and retry:

text A START TRANSACTION A UPDATE accounts SET balance = 0 WHERE id = 2 B UPDATE accounts SET balance = 1 WHERE id = 2 -> ERROR 1205 Lock wait timeout exceeded; try restarting transaction A ROLLBACK
sql SELECT @@innodb_lock_wait_timeout AS default_timeout_seconds;

Result:

default_timeout_seconds
50

SELECT ... FOR UPDATE

A plain SELECT takes no lock. To read a row and be sure nobody changes it before your update (check-then-act), lock it while reading:

sql START TRANSACTION; SELECT stock FROM products WHERE id = 1 FOR UPDATE; -- others wait if they try to change it -- application checks stock >= 1 UPDATE products SET stock = stock - 1 WHERE id = 1; COMMIT;

Often an atomic statement is better and needs no explicit lock:

sql UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock >= 1; SELECT ROW_COUNT() AS rows_changed;

Result:

rows_changed
1

If rows_changed is 0 there was not enough stock. This is the safest pattern for counters and inventory.

Gap and Next-Key Locks

Under REPEATABLE READ, a locking range query also locks the gaps between index records, to stop phantom rows. The table here holds ids 1, 2, 10, 20. Session A locks the range 5 to 15 and session B tries to insert id 12 (which lies in the gap):

text A START TRANSACTION A SELECT id FROM accounts WHERE id BETWEEN 5 AND 15 FOR UPDATE -> [[10]] B INSERT INTO accounts VALUES (12,'Eli',100) -> ERROR 1205 Lock wait timeout exceeded; try restarting transaction A ROLLBACK

The insert was blocked until it timed out, although id 12 does not exist. With READ COMMITTED there are no gap locks for these statements:

text A START TRANSACTION A SELECT id FROM accounts WHERE id BETWEEN 5 AND 15 FOR UPDATE -> [[10]] B INSERT INTO accounts VALUES (12,'Eli',100) A ROLLBACK
Why this matters Gap locks explain surprising blocking on busy tables and many deadlocks. Switching to READ COMMITTED removes most of them, at the price of phantom rows. Check your application's needs before changing it.

NOWAIT and SKIP LOCKED (8.0+)

OptionMeaning
NOWAITFail immediately (error 3572) if a row is locked
SKIP LOCKEDSkip locked rows and return only free ones

SKIP LOCKED turns a table into a work queue: many workers each grab different jobs with no waiting. Session A has row 1 locked:

text A START TRANSACTION A SELECT id FROM accounts WHERE id = 1 FOR UPDATE -> [[1]] B SELECT id FROM accounts ORDER BY id FOR UPDATE NOWAIT -> ERROR 3572 Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set. B START TRANSACTION B SELECT id FROM accounts ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED -> [[2], [10]] B ROLLBACK A ROLLBACK
sql -- worker loop START TRANSACTION; SELECT id FROM jobs WHERE status = 'new' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- process job... UPDATE jobs SET status = 'done' WHERE id = :id; COMMIT;

Seeing Locks

Two views help when something hangs. Both exist in MySQL 8:

sql SELECT COUNT(*) >= 0 AS data_locks_view_exists FROM performance_schema.data_locks;

Result:

data_locks_view_exists
1
sql SELECT * FROM performance_schema.data_locks; -- who holds which lock SELECT * FROM performance_schema.data_lock_waits; -- who waits for whom SELECT * FROM sys.innodb_lock_waits; -- readable summary SHOW PROCESSLIST; -- running sessions

Table Locks

LOCK TABLES t WRITE locks a whole table. It is rarely needed with InnoDB and blocks others heavily. Prefer row-level methods. FLUSH TABLES WITH READ LOCK freezes all writes and is used by some backup tools.

Common Beginner Mistakes

MistakeWhat happensFix
Long transactions holding locksEveryone queuesKeep them short
FOR UPDATE on a non-indexed columnLocks many rows or the whole tableLock by indexed key
Read, check, then write without a lockLost updates, oversold stockAtomic UPDATE ... WHERE stock >= n or FOR UPDATE
Ignoring error 1205Failing requestsRoll back and retry
Locking in different order in different codeDeadlocksSame order everywhere

Practice

  1. Reproduce the writer-blocks-writer test with two mysql windows.
  2. Lower innodb_lock_wait_timeout for one session and trigger error 1205.
  3. Write an atomic stock decrement that never goes below zero.
  4. Design a jobs table and a worker query with SKIP LOCKED.

Conclusion

InnoDB uses row locks that last until the end of the transaction. REPEATABLE READ adds gap locks, READ COMMITTED does not, FOR UPDATE locks what you read, and NOWAIT and SKIP LOCKED make queues and fast failures possible.

Quick Summary: row locks, lock timeout, FOR UPDATE, gap lock, next-key lock, NOWAIT, SKIP LOCKED.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators