MySQL Interview: Indexes, Transactions and Locks

B+ tree structure, index failure patterns, isolation levels, MVCC and row/gap locks — the core of almost every MySQL interview.

IntermediateUpdated 2026-10-2968K views

Indexes

Q1: Why B+ tree and not B tree / hash / red-black?

B+ tree: non-leaf nodes hold no data, only keys → huge fanout → a 3-level tree covers tens of millions of rows (page size 16KB). All data lives in leaf nodes linked in a linked list → range scans are sequential reads. Hash does point lookups fine but not ranges; red-black trees are binary → too tall for disk pages.

Q2: Clustered index vs secondary index.

The clustered index IS the table (leaf = whole row, InnoDB uses the PK or a hidden rowid). A secondary index leaf holds the PK value, so a non-covering select does a 'table lookup' (回表). Covering index = all selected columns already in the index → skip the lookup.

Q3: When does an index FAIL to be used?

  • Leftmost-prefix violation: composite index (a,b,c) but condition only on b/c
  • Functions/math on the column: WHERE YEAR(create_time), WHERE id+1=10
  • Implicit type conversion: varchar column compared to a number
  • LIKE with leading wildcard: LIKE '%abc'
  • OR across indexed and non-indexed columns
  • Optimizer decides scanning is cheaper (low selectivity / few rows)
Leading-wildcard LIKE and function-wrapped columns disable indexes because the index is sorted on the ORIGINAL value — a tree traversal on transformed values is impossible.

Transactions and isolation

Q4: The four anomalies and four isolation levels.

LevelDirty readUnrepeatablePhantom
READ UNCOMMITTED可能可能可能
READ COMMITTED不可能可能可能
REPEATABLE READ(InnoDB 默认)不可能不可能InnoDB 用间隙锁基本解决
SERIALIZABLE不可能不可能不可能

Q5: How does MVCC work?

Each row has hidden trx_id and roll_pointer; the undo log chains historical versions. Each transaction gets a read view (active transaction list) at its snapshot; a version is visible if its trx_id is committed before the view's min boundary. This lets reads see a consistent snapshot while writes create new versions — non-locking reads.

Q6: Record lock / gap lock / next-key lock.

  • Record lock: locks the index entry itself (a row)
  • Gap lock: locks the interval BETWEEN rows, only under RR, to stop INSERTs into that range
  • Next-key = record + the gap before it; default under RR
-- 间隙锁实战:事务 A
BEGIN;
SELECT * FROM orders WHERE id BETWEEN 100 AND 200 FOR UPDATE;   -- 锁住 100..200 及间隙
-- 事务 B 想插 id=150 → 阻塞;插 id=300 → 正常
-- 间隙锁只在 RR 存在,RC 下没有,所以 RC 更易并发也更易幻读
Gap locks can deadlock in surprising ways: two transactions each holding overlapping gaps and inserting into each other's territory are a classic. Keep 'lock then insert' order consistent across code paths.

Friends & Partners