skip to content

In MySQL InnoDB at REPEATABLE READ, what do record, gap and next-key locks cover, and what does a range SELECT ... FOR UPDATE lock?

level: middleimportance: must knowfreq 75%

answer

  1. locks live on index records
  2. the space between two keys
  3. record plus the gap before it
  4. unique equality skips the gap

basics

~20 s

InnoDB locks index records: a record lock covers one entry, a gap lock the space between entries, and a next-key lock both an entry and the gap before it, so a range FOR UPDATE blocks inserts anywhere in the scanned range.

solid answer

~40 s

InnoDB's row locks are really **index-record locks**. A **record lock** covers one index entry. A **gap lock** covers the space between two entries, or before the first or after the last, and only stops other transactions inserting there. A **next-key lock** is a record lock plus a gap lock on the gap before that record, and it is what `REPEATABLE READ` uses for searches and index scans, which is how InnoDB prevents phantom rows. So `SELECT ... WHERE warehouse_id BETWEEN 10 AND 20 FOR UPDATE` on a non-unique index locks every entry it scans and the gaps between them: an insert of 15 blocks whether or not 15 existed. A unique index searched for one row takes only a record lock, and a statement with no usable index locks every row it scans.

code

sql · 8 lines
sql
START TRANSACTION;
SELECT id FROM shipment WHERE warehouse_id BETWEEN 10 AND 20 FOR UPDATE;

SELECT INDEX_NAME, LOCK_TYPE, LOCK_MODE, LOCK_STATUS, LOCK_DATA
FROM performance_schema.data_locks
WHERE OBJECT_SCHEMA = DATABASE() AND OBJECT_NAME = 'shipment';

ROLLBACK;

go deeper

for a junior

Recall that InnoDB's row locks sit on index entries and that REPEATABLE READ also locks the gaps between them.

for a middle

Define record, gap and next-key locks with intervals, explain the unique-index exception, and say what a range FOR UPDATE blocks.

for a senior

Read data_locks or InnoDB status output to explain an unexpected wait, and use indexes to shrink what a statement locks.

for a principal

Decide where correctness depends on gap locking and whether constraints or explicit parent-row locks should carry those invariants instead.

## InnoDB locks index records, not rows In MySQL's InnoDB storage engine, row-level locks are set on **index records**. When a locking read (`SELECT ... FOR UPDATE` or `FOR SHARE`), an `UPDATE` or a `DELETE` searches or scans an index, it locks the index records it encounters. Three consequences follow straight away: - Even a table with no index is locked through the hidden clustered index InnoDB creates for it. - InnoDB does not remember the `WHERE` condition, only which index ranges were scanned. A statement with no suitable index scans the whole table and **locks every row**, which also blocks every insert by other sessions. - When the search uses a secondary index and the locks are exclusive, InnoDB also locks the matching clustered-index (primary key) records. ## The three lock shapes | Lock | Covers | What it blocks | `performance_schema.data_locks.LOCK_MODE` | |---|---|---|---| | **Record lock** | one index entry | changes to that entry and locks that conflict with it | `X,REC_NOT_GAP` or `S,REC_NOT_GAP` | | **Gap lock** | the open interval between two entries, or before the first / after the last | inserts into that interval only | `X,GAP` or `S,GAP` | | **Next-key lock** | an entry plus the gap before it | both of the above | `X` or `S` alone | Suppose a non-unique index on `warehouse_id` holds the values 10, 11, 13 and 20. The possible next-key intervals are `(-infinity, 10]`, `(10, 11]`, `(11, 13]`, `(13, 20]` and `(20, +infinity)`. The last one is anchored on the **supremum pseudo-record**, a marker above every real value, so in effect it locks only the gap after 20. Gap locks have two properties people get wrong: 1. They are **purely inhibitive**: their only job is to stop inserts into the gap. A shared and an exclusive gap lock do not conflict, and two transactions can hold gap locks on the same gap at the same time. 2. An insert into a locked gap is what waits. The inserting transaction first sets an **insert intention lock**, a special gap lock that conflicts with other transactions' gap and next-key locks on that gap but not with other inserts at different positions. ## What a range FOR UPDATE takes At `REPEATABLE READ`, InnoDB's default, a locking read with a range condition locks the index range it scans with next-key locks. For ```sql SELECT id FROM shipment WHERE warehouse_id BETWEEN 10 AND 20 FOR UPDATE; ``` the scan locks the entries for 10, 11, 13 and 20 together with the gaps before them, and InnoDB can also lock the gap after the last record it reads. Another session's `INSERT` with `warehouse_id = 15` therefore waits, whether or not 15 existed, and so does an insert of 12. Because the index is secondary and the locks are exclusive, the matching primary-key records are locked too. The exact boundary at the edges depends on the index and the release, so read it from `performance_schema.data_locks` rather than guessing. ## The exceptions that change the picture - **Unique index, unique search condition.** `SELECT * FROM shipment WHERE id = 100 FOR UPDATE` on the primary key takes a record lock on 100 and no gap lock. This exemption does not apply when the condition uses only some columns of a multi-column unique index. - **Non-unique or unindexed column.** The same equality on a non-unique index does lock the preceding gap. - **`READ COMMITTED`.** Gap locking is disabled for searches and index scans and kept only for foreign-key and duplicate-key checks, so phantoms become possible; record locks on rows that fail the `WHERE` condition are also released after it is evaluated. - **`SERIALIZABLE`.** Plain `SELECT`s become shared next-key locking reads when autocommit is disabled. - **Spatial indexes** use predicate locks instead, because multidimensional data has no single "next" key. ## Reading the locks back `performance_schema.data_locks` lists every lock InnoDB holds or waits for. `LOCK_TYPE` is `TABLE` or `RECORD`; table rows show intention modes such as `IX`. For a record lock on a secondary index, `LOCK_DATA` shows the secondary key with the primary key appended, and it shows `supremum pseudo-record` for the gap above the highest value. The same information appears in `SHOW ENGINE INNODB STATUS`, where a record-only lock reads `lock_mode X locks rec but not gap` and a plain `lock_mode X` is a next-key lock. Why phantoms matter and how predicate locking works in general is covered with phantom reads; the material here is InnoDB's own implementation of it.

  • Why does an InnoDB UPDATE with a WHERE on an unindexed column block inserts across the whole table?
    InnoDB locks the index records a statement scans, not the rows that satisfy the condition. With no usable index the `UPDATE` scans the entire clustered index, so at `REPEATABLE READ` it sets next-key locks on every record and every gap. Adding an index on the filtered column shrinks the scanned range and therefore the locked range.
  • How can InnoDB's next-key locking enforce a check that a row does not exist yet?
    If you read with `FOR SHARE` or `FOR UPDATE` and find no duplicate, the gap or next-key lock taken during that search stops anyone inserting a matching row until you commit. The manual describes this as locking the nonexistence of something. A unique constraint is usually simpler, and the protection disappears at `READ COMMITTED`.

A gap lock is like a note on a sign-up sheet saying no new names may be squeezed in between two existing ones. It does not stop anyone editing the names already there, and two people can pin the same note without arguing; it only stops someone writing a new name into that space.

  • InnoDB locks the rows that match the WHERE clause, not the index records scanned.
  • An exclusive gap lock conflicts with another transaction's gap lock on the same gap.
  • A gap lock stops other transactions updating the records on either side of it.
  • A primary-key equality lookup that finds its row also locks the gap before it.
  • InnoDB escalates many row locks into a table lock when a scan is large.