Part 12 / Topic 6 of 9
Row and table locks
Locks are how conflicting work queues up. The two kinds you'll actually reason about:
- Row locks — an UPDATE/DELETE locks the rows it touches until commit. Another writer wanting those rows waits; everything else proceeds.
- Table locks — DDL mostly.
ALTER TABLEand friends take strong table-level locks;TRUNCATEtakes the strongest (ACCESS EXCLUSIVE). This is why "quick" migrations stall busy systems — Stage 4 returns to it.
The live view of who holds and who waits is pg_locks (joined to pg_stat_activity for the who). A query you'll want saved the first time production "hangs":
SELECT locktype, relation::regclass AS table, mode, granted, pid
FROM pg_locks
WHERE relation = 'products'::regclass;
locktype | table | mode | granted | pid
----------+-------+------+---------+-----
(0 rows)
(Quiet here — nothing is locked right now; during section 7's transcripts this view shows one granted = t and one granted = f row, the waiter.) The operational rule that falls out: keep transactions short. Locks live until COMMIT — an open psql prompt holding BEGIN is a queue of blocked writers growing behind one forgotten window.
🧪 Quick quiz — answer from memory, then check.
- What does an UPDATE lock, and until when?
- Why are long-lived transactions operationally dangerous?
Show the answers
- The rows it changed, until the transaction commits or rolls back.
- They hold row locks (blocking writers) and pin the snapshot horizon (blocking VACUUM) the entire time.
Done here? The practice set for Part 12 — 6 exercises with solutions — is on the part page.