Skip to the page

PostgreSQL and MySQL inside · mid

InnoDB inside: clustered index, undo log and gap locks

InnoDB stores a table as a B+ tree on the primary key, keeps old versions in an undo log and, at its default isolation level, locks gaps between index records. These three facts explain many MySQL surprises.

The notes

What you must know

  • The table is stored as a B+ tree on the primary key. If there is none, InnoDB uses the first NOT NULL unique index, or a hidden row id. This is the clustered index.
  • A secondary index stores the primary key value, not a row address. A lookup goes secondary index first, then the primary key tree. A wide primary key makes every secondary index bigger.
  • A random primary key (for example UUIDv4) inserts all over the tree: page splits and cache misses. A sequential key (bigint, or a time-ordered UUID such as UUIDv7) appends at the end.
  • PostgreSQL is different: the table is a heap with no order, and every index points to a tuple id.
  • The default isolation level is REPEATABLE READ. A locking read on a range takes next-key locks: each index record plus the gap before it.
  • A gap lock blocks inserts into the gap. So an INSERT of id 15 can wait while another session holds FOR UPDATE on the range 10 to 20, even if no row 15 exists. The waiting session fails with error 1205 after innodb_lock_wait_timeout (50 seconds by default).
  • Two sessions can both hold a gap lock, and then each insert waits for the other: a deadlock. Fix: a unique key with INSERT ... ON DUPLICATE KEY UPDATE, or READ COMMITTED, where gap locking is mostly off.
  • See locks with performance_schema.data_locks and data_lock_waits, and SHOW ENGINE INNODB STATUS. PostgreSQL has no gap locks.

The red pen

Common traps: mistake → fix

  • Mistake: Only PostgreSQL has MVCC

    Fix: InnoDB has it too, with an undo log.

  • Mistake: A lookup by secondary index goes straight to the row

    Fix: it first reads the primary key, then the clustered tree.

  • Mistake: An insert waiting means a row with that id exists

    Fix: it can wait on a gap lock for a range that is empty.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a clustered index?
  2. How does InnoDB store a table, and how is that different from PostgreSQL?
  3. Why is a random UUID a poor primary key in InnoDB?
  4. Why does an INSERT hang when no row with that id exists?
  5. How do you remove gap locks, and what do you give up?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview