Locks, SELECT … FOR UPDATE & Deadlocks
Locks happen automatically
UPDATE/DELETElock the rows they change until the transaction ends- Other writers to the same rows wait; readers are not blocked (thanks to MVCC)
- DDL like
ALTER TABLE/DROPtakes stronger table locks that can block everything
Explicit row locks
| Clause | Meaning |
|---|---|
SELECT … FOR UPDATE | lock rows I'm about to change; others wait |
FOR NO KEY UPDATE | slightly weaker; doesn't block inserts of rows referencing this one |
FOR SHARE | others can read-lock too, but can't modify |
… NOWAIT | fail immediately instead of waiting |
… SKIP LOCKED | skip rows that are locked (great for job queues) |
Pattern: check, then change safely ("pessimistic locking")
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- lock the row
-- app checks: enough money?
UPDATE accounts SET balance = balance - 300 WHERE id = 1;
COMMIT; -- lock released
Job queue with SKIP LOCKED ⭐
Several workers each grab a different pending job without blocking each other:
SELECT … FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED
Deadlocks
Transaction A locks row 1 and waits for row 2; transaction B locks row 2 and waits for row 1 → both wait forever. PostgreSQL detects this (after deadlock_timeout, 1 s by default) and aborts one of them with a deadlock error.
Avoiding deadlocks
- Always lock rows in a consistent order (e.g. by id ascending)
- Keep transactions short
- Lock everything you need up front:
SELECT … WHERE id IN (1, 2) ORDER BY id FOR UPDATE - Retry the transaction on a deadlock error (SQLSTATE
40P01)
Seeing locks and waiting queries
pg_locks, pg_stat_activity (wait_event_type = 'Lock'), and pg_blocking_pids(pid)
Advisory locks
Application-defined locks on any number: pg_advisory_xact_lock(42) — e.g. "only one monthly report job at a time".
Example
-- Pessimistic locking: safely withdraw only if there's enough money
CREATE FUNCTION withdraw(p_account INT, p_amount NUMERIC) RETURNS TEXT
LANGUAGE plpgsql AS $$
DECLARE current_balance NUMERIC;
BEGIN
SELECT balance INTO current_balance
FROM accounts WHERE id = p_account
FOR UPDATE; -- other withdrawals now wait here
IF current_balance < p_amount THEN
RETURN format('Declined: balance %s < %s', current_balance, p_amount);
END IF;
UPDATE accounts SET balance = balance - p_amount WHERE id = p_account;
RETURN format('OK: new balance %s', current_balance - p_amount);
END $$;
SELECT withdraw(6, 1000); -- OK: new balance 1500.00
SELECT withdraw(6, 9999); -- Declined: balance 1500.00 < 9999
-- Job queue: each worker grabs a different job (SKIP LOCKED)
CREATE TABLE jobs (id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, task TEXT, status TEXT DEFAULT 'pending');
INSERT INTO jobs (task) VALUES ('send bill reminder'), ('monthly report'), ('backup');
WITH next_job AS (
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED -- a second worker would skip this row
)
UPDATE jobs SET status = 'running'
FROM next_job WHERE jobs.id = next_job.id
RETURNING jobs.id, jobs.task; -- 1 | send bill reminder
-- Avoid deadlocks: lock both accounts in a consistent order (by id)
BEGIN;
SELECT id, balance FROM accounts WHERE id IN (3, 1) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 1000 WHERE id = 3;
UPDATE accounts SET balance = balance + 1000 WHERE id = 1;
COMMIT;
-- Deadlock (two sessions, opposite order) — DON'T do this:
-- A: BEGIN; UPDATE accounts … WHERE id = 1;
-- B: BEGIN; UPDATE accounts … WHERE id = 3;
-- A: UPDATE accounts … WHERE id = 3; -- waits for B
-- B: UPDATE accounts … WHERE id = 1; -- waits for A → ERROR: deadlock detected
-- Who is waiting on whom right now?
SELECT pid, state, wait_event_type, left(query, 40) AS query, pg_blocking_pids(pid) AS blocked_by
FROM pg_stat_activity
WHERE datname = current_database() AND pid <> pg_backend_pid();
-- Advisory lock: only one "monthly report" at a time
SELECT pg_try_advisory_lock(2026) AS got_lock; -- true
SELECT pg_advisory_unlock(2026);