Locks & Deadlocks
Learn how row locks make writers wait, why readers do not, how two sessions can block each other forever, and how to prevent it.
A row you change is locked until you finish
When a transaction updates or deletes a row, PostgreSQL puts a row lock on it. Any other transaction that wants to change the same row has to wait until the first one commits or rolls back.
Row locks only block writers. A plain SELECT is never blocked by them, and never blocks anyone: it simply reads the last committed version of the row.
Locks keep changes from colliding
Without a lock, two sessions could both read a balance of 100 and each write back their own total, and one of the changes would be lost. The lock makes the second one wait and then work with the new value.
Waiting is normal
Session A runs UPDATE accounts SET balance = balance + 10 WHERE name = 'Alice' inside a transaction. Session B runs the same statement on the same row. B waits. When A commits, B's update runs.
If both sessions touch the rows in the same order, Alice first and then Bob, the second one only waits for a while and everything finishes.
A reader meets a writer: B has updated Alice but not committed, and A runs a SELECT on Alice. A gets the last committed value at once. It does not wait.
Watch the locks
Run Opposite order and look at the waits table just before the error. Then run Same order, and A reader meets a writer.
| sessiontext | statustext |
|---|---|
| A | idle |
| B | idle |
| rowtext | locked bytext |
|---|
| sessiontext | wantstext | held bytext |
|---|
Pick a story and press Next step. Watch the tables: who holds a row, and who is waiting.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- An UPDATE or DELETE locks the row until the transaction ends, and other writers wait.
- Readers never wait for writers, and writers never wait for readers.
- Two sessions waiting for each other is a deadlock. PostgreSQL aborts one with deadlock detected (40P01), and you retry it.
- Prevent deadlocks: update rows in the same order, keep transactions short.
Done with this concept?
Mark it complete to track your progress. No login needed.