MySQL Locks
Global Locks
Typically used for full backups. Blocks writes and allows only reads, so usually run during off-peak.
| |
Table-Level Locks
Table Locks
- Shared read lock: multiple threads can read the table concurrently, but cannot write. MyISAM uses a shared read lock for reads; InnoDB prefers row locks and MVCC for reads.
- Exclusive write lock: only one thread can acquire it; others cannot read or write.
| |
DDL such as ALTER/DROP/TRUNCATE triggers table locks.
Intention Locks
Intention locks are table-level locks to avoid full-table scans when checking for conflicts. InnoDB does NOT set intention locks for MVCC-consistent reads of a single record.
Intention locks do not conflict with row locks, nor with each other.
| Lock Type | Table S (Shared) | Table X (Exclusive) | Table IS (Intention S) | Table IX (Intention X) |
|---|---|---|---|---|
| Table S | Compatible | Conflict | Compatible | Compatible |
| Table X | Conflict | Conflict | Conflict | Conflict |
| Table IS | Compatible | Conflict | Compatible | Compatible |
| Table IX | Conflict | Conflict | Compatible | Compatible |
IS (Intention Shared)
| |
When reading a row in this mode, a row-level shared lock is set, and the table gets an IS lock.
- Another thread attempting a row-level X (write) lock checks via the index; if the row isn’t locked, it can lock; if it is, it must wait.
- Another thread attempting a table-level X lock sees the table already has an IS lock and cannot proceed.
- Another thread applying S (row/table) locks doesn’t conflict.
IX (Intention Exclusive)
| |
This sets an IX on the table and a row-level X lock on the target row(s).
- Another thread attempting a row-level X lock checks the index; if the row isn’t X-locked, it can lock; otherwise it waits.
- Another thread attempting a table-level X lock sees IX and cannot proceed.
- Another thread attempting a row-level S lock conflicts if it’s the same row; otherwise OK.
- Another thread attempting a table-level S lock is allowed.
Row Locks
Row locks are per-record.
Record Lock
Row-level S/X locks.
Gap Lock
Locks the gaps between index records (ranges can be open/closed on either side). Only in RR isolation for InnoDB, used to prevent phantom inserts.
May lead to deadlocks.
Next-Key Lock
A combination of record+gap locks; locks a half-open interval (left-open, right-closed). Prevents phantoms while also locking specific rows.
Interview Tips
- UPDATE without WHERE: InnoDB acquires table IX plus X on all rows to ensure atomicity/consistency; MyISAM takes a table-level X lock that blocks all reads/writes.
- UPDATE with WHERE: InnoDB locks matching rows with X and adds gap locks in RR to prevent phantoms. If the WHERE uses an index, it locks via the index; without an index, it may escalate to a table lock. MyISAM still takes a table-level X lock regardless.