Video in progress

Which commands take the table-level lock modes (`ACCESS SHARE`, `ROW EXCLUSIVE`, `SHARE`, `ACCESS EXCLUSIVE`), and which of them conflict with each other?

Every SQL command takes some lock on the table: SELECT takes the lightest, ACCESS SHARE, DML takes ROW EXCLUSIVE, and many ALTER TABLE forms and DROP take the heaviest, ACCESS EXCLUSIVE. Ordinary reads and writes don't block each other, but ACCESS EXCLUSIVE conflicts with everything.

📖 Answer

A short table for everyday commands:

Command Table lock
SELECT ACCESS SHARE
SELECT ... FOR UPDATE/SHARE ROW SHARE
INSERT, UPDATE, DELETE ROW EXCLUSIVE
VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY SHARE UPDATE EXCLUSIVE
CREATE INDEX SHARE
ALTER TABLE (many forms), DROP, TRUNCATE, VACUUM FULL ACCESS EXCLUSIVE

The important conflicts:

  • SHARE (a plain CREATE INDEX) conflicts with ROW EXCLUSIVE: while the index is being built, INSERT/UPDATE wait, while SELECT keeps working;
  • SHARE UPDATE EXCLUSIVE conflicts with itself: two VACUUMs or CREATE INDEX CONCURRENTLY can't run on one table at the same time;
  • ACCESS EXCLUSIVE conflicts with everything, even a plain SELECT.

Table locks are held until the end of the transaction. That means a session that did BEGIN; SELECT * FROM orders; ... and left it also keeps its ACCESS SHARE and makes an ALTER TABLE wait.

To see who is holding what right now:

SELECT l.pid, l.mode, l.granted, a.query
FROM pg_locks l
JOIN pg_stat_activity a USING (pid)
WHERE l.relation = 'orders'::regclass;

Before I write a migration, I check in the docs which lock the command takes: every form of ALTER TABLE is different.