#relation-lock-modes
What relation lock modes are there, and which of them conflict?
What to say
A table has eight lock modes from ACCESS SHARE to ACCESS EXCLUSIVE, lined up by strength. A plain `SELECT` takes the weakest, ACCESS SHARE; `INSERT`/`UPDATE`/`DELETE` take ROW EXCLUSIVE; commands like `CREATE INDEX` take SHARE; most `ALTER TABLE`, `DROP`, `TRUNCATE`, and `VACUUM FULL` take the strongest, ACCESS EXCLUSIVE, which conflicts with everything, including a plain SELECT. It is not the commands that conflict but the modes: reads are compatible with each other, while ACCESS EXCLUSIVE is compatible with nothing. An incompatible request gets into the queue.
What they want to hear
A senior should: - understand that locks are taken in modes and the conflict is decided by a compatibility table, not by the command name - know the key pairs: SELECT takes ACCESS SHARE, DML takes ROW EXCLUSIVE, heavy DDL takes ACCESS EXCLUSIVE - explain that ACCESS EXCLUSIVE blocks even readers, which is the danger of DDL on a hot table - be able to inspect current locks and waits through `pg_locks` and `pg_stat_activity`
Pitfalls
- ✗ Thinking a `SELECT` blocks nothing. It holds ACCESS SHARE, and that is enough to block ACCESS EXCLUSIVE
- ✗ Assuming relation locks are about rows. These are locks on the whole table as an object
- ✗ Confusing a mode's strength with a command name. The conflict is decided by the compatibility table of modes
Follow-up
- ? Why can a long `SELECT` delay an `ALTER TABLE`?
- ? Which mode does a plain `UPDATE` take?
- ? How do you tell from `pg_locks` who is waiting on whom?
Depth in knowledge base