Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

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 TABLE and friends take strong table-level locks; TRUNCATE takes 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.

  1. What does an UPDATE lock, and until when?
  2. Why are long-lived transactions operationally dangerous?
Show the answers
  1. The rows it changed, until the transaction commits or rolls back.
  2. 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.

Search the guide