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

Part 12 / Topic 7 of 9

FOR UPDATE and SKIP LOCKED

SELECT ... FOR UPDATE locks the rows it reads — "I'm going to write this; nobody touch it." The lost update, fixed, for real:

-- Session A                                   -- Session B
BEGIN;
SELECT stock FROM products
WHERE product_id = 1 FOR UPDATE;   → 15
                                               BEGIN;
                                               SELECT stock FROM products
                                               WHERE product_id = 1 FOR UPDATE;
                                               …blocks, waiting for A…
UPDATE products SET stock = 14
WHERE product_id = 1;
COMMIT;
                                               → 14      ← unblocked, sees A's result
                                               UPDATE products SET stock = 13
                                               WHERE product_id = 1;
                                               COMMIT;

B's read waited, then saw 14 — the race is gone, serialised at exactly one row. Add SKIP LOCKED and waiting turns into skipping: rows someone else holds are passed over. That one clause is the standard Postgres job queue — two workers claiming work simultaneously, no collision, no waiting:

-- Worker A                                    -- Worker B
BEGIN;                                         BEGIN;
UPDATE jobs SET status = 'running'             UPDATE jobs SET status = 'running'
WHERE id = (SELECT id FROM jobs                WHERE id = (SELECT id FROM jobs
  WHERE status = 'queued' ORDER BY id            WHERE status = 'queued' ORDER BY id
  FOR UPDATE SKIP LOCKED LIMIT 1)                FOR UPDATE SKIP LOCKED LIMIT 1)
RETURNING id, task;                            RETURNING id, task;
 id |    task                                   id |     task
----+------------                              ----+--------------
  1 | send_email                                 2 | resize_image
COMMIT;                                        COMMIT;

Same statement, same instant, different jobs — A locked job 1, so B's subquery skipped it and claimed job 2. (The jobs table behind this transcript: id, task, status default 'queued'.)

🧪 Quick quiz — answer from memory, then check.

  1. What changes when a plain SELECT gains FOR UPDATE?
  2. Why is FOR UPDATE SKIP LOCKED the queue idiom?
Show the answers
  1. The selected rows are locked like an UPDATE's — concurrent writers (and other FOR UPDATEs) wait.
  2. Each worker claims the first unclaimed row without waiting on the others — parallel consumers, zero collisions.

Done here? The practice set for Part 12 — 6 exercises with solutions — is on the part page.

Search the guide