Locks, FOR UPDATE & Deadlocks in SQL
Ordered locking + retry — pessimism with discipline
Writers take row locks; DDL takes strong table locks; SELECT … FOR UPDATE locks chosen rows for the txn (pessimistic read-modify-write guard). NOWAIT/SKIP LOCKED avoid blocking (queue-skipping jobs). Deadlock: two txns want each other’s locks — engine detects cycle, aborts one (retryable); prevention is consistent lock order (parents before children, id order) + short txns.
Row locks on write
UPDATE/DELETE lock touched rows till COMMIT/ROLLBACK — readers (MVCC) unaffected.
FOR UPDATE guards
SELECT … FOR UPDATE claims rows for staged multi-statement invariants.
SKIP LOCKED queues
Workers claim without blocking — NOWAIT errors instead of waiting.
Order + retry doctrine
Parents before children, id order everywhere; short txns; retry victims whole.
1BEGIN;2SELECT balance FROM accounts WHERE id IN (1,2) ORDER BY id FOR UPDATE;
| pattern | risk |
|---|---|
| ordered locks | no cycle possible |
| random order | deadlock risk |
Both transfer directions lock 1 then 2 — never 2-then-1 vs 1-then-2. The cycle cannot form; the engine never must choose a victim.
Ordered transfer locks
Cycle impossible by construction.
1BEGIN;2SELECT balance FROM accounts WHERE id IN (1,2) ORDER BY id FOR UPDATE;
| order | effect |
|---|---|
| lock 1 then 2 | both paths agree |
Queue claim without blocking
Concurrent workers skip claimed rows.
1SELECT * FROM jobs WHERE status = 'queued' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1;
| worker | claimed |
|---|---|
| worker A | job 101 |
| worker B | job 102 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.