Sub topic 11
Locking and SELECT ... FOR UPDATE
This chapter assumes you know BEGIN, COMMIT and ROLLBACK, and that you have seen the anomalies from the previous chapters, especially lost updates. The examples use PostgreSQL syntax. Other databases have similar features with different details.
Why locks exist
Isolation levels describe what a transaction is allowed to observe. Locks are one mechanism the database uses to enforce those rules. A lock is a marker that a transaction places on a resource, such as a row or a table. Other transactions that want a conflicting lock must wait until the first transaction commits or rolls back.
Locks are held until the end of the transaction. They are released at COMMIT or ROLLBACK, not when the statement that took them finishes. This is why long transactions cause so much waiting.
Shared and exclusive locks
The two basic lock modes are:
- Shared lock (S): taken to read. Many transactions can hold a shared lock on the same item at once.
- Exclusive lock (X): taken to write. Only one transaction can hold it, and it conflicts with every other lock on that item.
| Held by transaction 1 | Requested by transaction 2 | Result |
|---|---|---|
| Shared | Shared | Granted |
| Shared | Exclusive | Waits |
| Exclusive | Shared | Waits |
| Exclusive | Exclusive | Waits |
Classic lock-based databases take shared locks on every read. PostgreSQL does not. Its plain SELECT takes no row locks at all, because it reads from a snapshot (the next chapter covers MVCC). PostgreSQL does take row-level locks in two cases: when you write, and when you ask for a lock explicitly.
Implicit locks on writes
Every UPDATE and DELETE locks the rows it changes. A second transaction that tries to change the same row waits.
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
-- row 1 is now locked by A
-- Session B
BEGIN;
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- blocks until A commits or rolls backWhen A commits, B resumes. Under READ COMMITTED, B re-reads the new version of the row and applies its change to that version. Under REPEATABLE READ or SERIALIZABLE, B instead fails with a serialization error, because the row changed after B's snapshot was taken.
The read-then-write problem
Plain reads do not lock rows, so this common pattern is unsafe:
- SELECT the balance.
- Compute a new value in application code.
- UPDATE the row with that value.
Two sessions can both read 100 and both write back their own result. One update is lost. The UPDATE itself locks the row, but only after both reads are finished.
There are two ways to fix this. The first is to avoid the separate read and let the database do the arithmetic:
UPDATE accounts SET balance = balance - 20 WHERE id = 1;This single statement reads and writes under the row lock, so it is safe. The second way is needed when the application must look at the data before deciding what to write. In that case, lock the row at read time.
SELECT ... FOR UPDATE
Adding FOR UPDATE to a SELECT makes it lock each returned row as if it were about to be updated.
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- Other transactions that try to update or lock this row now wait.
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
COMMIT;If another transaction already holds a lock on row 1, the SELECT waits. Once it gets the lock, it returns the latest committed version of the row, even under READ COMMITTED. The decision you make from that value is therefore based on data nobody else can change before you commit.
A typical use is a withdrawal that must check the balance in application code:
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- Application checks: balance >= 20 ? continue : ROLLBACK
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
COMMIT;Lock only the rows you need. FOR UPDATE on a query with a broad WHERE clause locks every matching row and blocks other writers for the length of your transaction.
Row lock strengths in PostgreSQL
PostgreSQL offers four row-level strengths. Weaker ones conflict with fewer others.
| Clause | Use it when | Conflicts with |
|---|---|---|
| FOR UPDATE | You will update or delete the row | All four modes |
| FOR NO KEY UPDATE | You will update non-key columns | FOR SHARE, FOR NO KEY UPDATE, FOR UPDATE |
| FOR SHARE | You need the row to stay unchanged, but others may also read-lock it | FOR UPDATE, FOR NO KEY UPDATE |
| FOR KEY SHARE | You only need the row's key to stay stable (foreign key checks use this) | FOR UPDATE |
An ordinary UPDATE that does not touch key columns takes FOR NO KEY UPDATE automatically. This lets it run alongside foreign key checks from other tables, which only take FOR KEY SHARE.
Controlling waiting: NOWAIT and SKIP LOCKED
By default a locking read waits as long as it must. Two modifiers change that.
NOWAITraises an error immediately if any selected row is locked.SKIP LOCKEDsilently skips rows that are locked and returns the others.
SKIP LOCKED is the standard way to build a job queue in SQL, because each worker claims a different row:
BEGIN;
SELECT id, payload
FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- process the job, then:
UPDATE jobs SET status = 'done' WHERE id = 1; -- use the id returned above
COMMIT;Two workers running this at the same time never get the same job. SKIP LOCKED returns an incomplete view of the table by design, so use it for queues and not for reports.
You can also set a ceiling on waiting for the whole session with SET lock_timeout = '2s';. A statement that waits longer fails with an error instead of hanging.
Table locks
Row locks are not the only kind. Every statement also takes a lock on the whole table, in a mode that matches what it does. A SELECT takes ACCESS SHARE, an UPDATE takes ROW EXCLUSIVE, and these do not conflict with each other. Schema changes such as ALTER TABLE take ACCESS EXCLUSIVE, which conflicts with everything, including plain SELECTs.
LOCK TABLE accounts IN SHARE MODE;You rarely need LOCK TABLE in application code. The practical consequence is for migrations. An ALTER TABLE waits behind any open transaction that touched the table, and while it waits, every new query on that table queues behind it. A forgotten open transaction can therefore stall a whole application. Setting a short lock_timeout before a migration makes it fail fast instead.
Seeing who is blocked
PostgreSQL shows lock waits in the pg_locks view and in pg_stat_activity. This query lists blocked sessions and the sessions blocking them:
SELECT pid,
pg_blocking_pids(pid) AS blocked_by,
wait_event_type,
state,
query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;A session in the state idle in transaction that appears in a blocked_by list is the usual cause: the application opened a transaction, took locks and then stopped doing work.
Lock waits in a diagram
Common errors
- Locking too late. Reading with a plain SELECT and locking afterwards does not protect the earlier read.
- Locking too much.
FOR UPDATEwithout a selective WHERE clause blocks unrelated work. - Holding locks during slow work. Calling an external service between the lock and the COMMIT keeps the row locked for as long as that call takes.
- Locking rows in inconsistent order. If one code path locks row 1 then row 2 and another locks row 2 then row 1, they can deadlock. The deadlocks chapter covers detection and avoidance.
- Expecting FOR UPDATE to lock rows that do not exist. It locks only existing rows. It does not stop another session from inserting a new matching row, which is how phantoms and some write skew cases still occur. Use SERIALIZABLE, a unique constraint, or a lock on a parent row for those cases.
Exercise
Two workers run "SELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 1 FOR UPDATE" at the same moment, without SKIP LOCKED. What happens to the second worker, and how does adding SKIP LOCKED change it?
Show answer
The second worker blocks on the row the first worker locked and waits until the first commits or rolls back. Once the first worker commits and marks the job as done, the second re-checks the row, finds it no longer matches status = 'pending', and may return no row at all, so the workers are serialized. With SKIP LOCKED the second worker skips the locked row and immediately claims the next pending job, so both workers run in parallel on different jobs.
Exercise
A migration runs ALTER TABLE accounts ADD COLUMN note text while one session sits "idle in transaction" after reading from accounts. Why do unrelated queries on accounts start to hang, and what setting reduces the damage?
Show answer
ALTER TABLE needs an ACCESS EXCLUSIVE table lock, which conflicts with the lock held by the idle transaction, so it waits. New queries on the table queue behind the waiting ALTER TABLE, so they hang too. Setting a short lock_timeout before the migration makes the ALTER TABLE fail quickly instead of blocking the table. Ending or fixing the idle transaction removes the root cause.