Skip to main content
InterviewHubPRO
Section Overview
Q38

Question 38 of 50

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

76%
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:

  1. Record Lock: Locks a specific existing index record (WHERE id = 5 FOR UPDATE).
  2. 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.
  3. 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;