Row-Level Locking (SELECT ... FOR UPDATE, FOR SHARE, SKIP LOCKED)
Lock rows for updates, share locks for reads, and skip locked work queues.
In plain words
FOR UPDATE says "these rows are mine until I'm done". SKIP LOCKED says "if someone else has a row, I'll take a different one".
Think of it like…
Taking a ticket from the deli counter dispenser: once you hold ticket 42, nobody else can be served for it (FOR UPDATE). SKIP LOCKED is the next customer simply taking ticket 43 instead of waiting for you.
Where you’ve seen it
Worker processes pull jobs from a table: BEGIN; SELECT id, payload FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED; then mark them done and COMMIT. Ten workers running this at once each get different jobs, with no waiting and no double-processing.
Words you’ll hear
- FOR UPDATE
- Exclusive row lock: blocks other updates, deletes and FOR UPDATE / FOR SHARE on those rows.
- FOR SHARE
- Shared lock: others can also FOR SHARE, but no one can update or delete.
- NOWAIT
- Raise an error immediately if a row is already locked.
- SKIP LOCKED
- Leave out rows that are already locked (PostgreSQL 9.5+, MySQL 8.0+).
Visual diagram
Theory & example queries
Preventing read-then-write races
Without a lock, two transactions can both read stock = 1, both decide there's enough, and both decrement. With SELECT stock FROM products WHERE id = 7 FOR UPDATE, the second transaction waits until the first commits, then reads the updated value. In PostgreSQL and InnoDB, ordinary SELECTs aren't blocked by these locks; they keep reading the last committed data.
Often you don't need an explicit lock: a single atomic statement such as UPDATE products SET stock = stock - 1 WHERE id = 7 AND stock > 0 does the check and the write together. Use FOR UPDATE when the decision needs logic in between (calling another service, checking several rows).
| id | owner | balance |
|---|---|---|
| 1 | Maya | 1000 |
| 2 | Ravi | 500 |
BEGIN;SELECT balanceFROM accountsWHERE id = 1FOR UPDATE;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
UPDATE accountsSET balance = balance - 500WHERE id = 1;COMMIT;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative transaction responses4 sample rows
| step | response |
|---|---|
| BEGIN | BEGIN |
| locked balance | 5000 |
| UPDATE | UPDATE 1 |
| COMMIT | COMMIT |
Note: The sample account starts with balance 5000 and the application approves a 500-unit withdrawal. Actual result types and command tags are dialect-dependent, and concurrent locking may cause a wait or error.
then, after the application checks the balance,
Key takeaway: Lock the rows you'll change before deciding, or do it in one atomic UPDATE.
NOWAIT, SKIP LOCKED and job queues
By default, a FOR UPDATE on a locked row waits. NOWAIT turns that into an immediate error, which suits user-facing actions ("someone else is editing this, try again"). SKIP LOCKED returns only the rows nobody holds, which is exactly what concurrent queue workers want.
For a queue, combine it with ORDER BY and LIMIT so each worker takes a small batch, process quickly, and commit to release the locks. An index on the filter (WHERE status = 'pending') keeps the lookup fast; a partial index on pending rows works well. PostgreSQL also has lighter FOR NO KEY UPDATE and FOR KEY SHARE modes that conflict less with foreign key checks.
UPDATE jobsSET status = 'running', started_at = now()WHERE id IN ( SELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED )RETURNING id, payload;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative claimed jobs2 sample rows
| id | payload |
|---|---|
| 101 | {"type":"send_email","user_id":42} |
| 104 | {"type":"resize_image","asset_id":17} |
Note: Sample pending jobs are illustrative. RETURNING contains only jobs actually changed by this worker, up to the LIMIT of 10; SKIP LOCKED may make another run claim a different set.
Key takeaway: NOWAIT fails fast; SKIP LOCKED turns a table into a safe work queue.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Start a transaction
Row locks last until the transaction ends, so the read, the decision and the write must be inside one transaction.
BEGIN;When to use it & trade-offs
What it is
SELECT … FOR UPDATE locks the rows it returns until the transaction ends, so no other transaction can update, delete or lock them in the meantime. FOR SHARE takes a weaker lock that still blocks writers. NOWAIT fails immediately instead of waiting, and SKIP LOCKED simply skips rows another transaction has locked.
Why it matters: Read-then-write logic (check stock, then decrement; check balance, then withdraw) is racy without a lock. And FOR UPDATE SKIP LOCKED is the standard way to build a job queue in PostgreSQL or MySQL 8, letting many workers each grab different jobs without stepping on each other. Both come up in backend interviews.
When to reach for it
- Inventory, seat booking and balance updates with logic in between
- Database-backed job queues
- "Someone else is editing this" checks with NOWAIT
When to avoid or be careful
- Holding row locks while calling external APIs or waiting on users
- FOR UPDATE when a single atomic UPDATE would do
- SKIP LOCKED for reports that need to see every row
Ways to avoid read-then-write races
Strengths: No explicit lock, a single round trip.
Watch out: Only works when the check fits in the WHERE clause.
Strengths: Guarantees nobody changes the rows meanwhile.
Watch out: Others wait; long transactions cause contention and deadlocks.
Strengths: Workers never block each other or take the same job.
Watch out: Intentionally inconsistent view: locked rows are invisible to that query.
Interview signals & numbers to know
When this topic comes up
- “Two users bought the last item”
- “Build a job queue in Postgres”
- SELECT FOR UPDATE
- Lock waits and timeouts
- Workers processing the same job twice
Benchmarks & rules of thumb
- PostgreSQL 9.5
- SKIP LOCKED added
- MySQL 8.0
- SKIP LOCKED and NOWAIT added
- COMMIT
- releases all row locks
Common mistakes & follow-ups
Common interview mistakes
- Running SELECT … FOR UPDATE in autocommit mode, where the lock is released immediately after the statement.
- Building a queue with plain SELECT then UPDATE, so two workers pick up the same job.
- Keeping a transaction open across a slow HTTP call while other users wait on the lock.
Likely interviewer follow-ups
- How would you build a job queue in PostgreSQL that several workers can use safely?
- What's the difference between FOR UPDATE and FOR SHARE?
- When would you choose an atomic UPDATE over SELECT … FOR UPDATE?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Row-Level Locking (SELECT ... FOR UPDATE, FOR SHARE, SKIP LOCKED) with hands-on SQL practice and interview Q&A.