MySQL & InnoDB (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
InnoDB Locking: Record Locks, Gap Locks, and Next-Key Locks.
senior LevelCode ExampleMySQL
In Simple Words:
To prevent Phantom Reads under the default REPEATABLE READ isolation level, InnoDB uses three locking mechanisms:
- Record Lock: Locks a specific existing index record (
WHERE id = 5 FOR UPDATE). - Gap Lock: Locks the empty gap between index records (or before the first / after the last record) to prevent other transactions from inserting new rows into the gap.
- Next-Key Lock: Combination of a Record Lock on the index record plus a Gap Lock on the gap preceding it.
sql
-- Next-Key Lock example
-- If rows exist with id=10 and id=20, this query locks the record 20 AND the gap (10, 20],
-- blocking any concurrent INSERT of id=15!
SELECT * FROM orders WHERE id = 20 FOR UPDATE;