Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 145/ 160
08. Transactions, Security & Production SQL Administration

Row-Level Locking (SELECT ... FOR UPDATE, FOR SHARE, SKIP LOCKED)

Lock rows for updates, share locks for reads, and skip locked work queues.

AdvancedFOR UPDATE · FOR SHARE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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).

Lock, check, updateQuery example
1Input dataStart from the source rows or state that the statement sees.
accounts
2 rows
accounts sample rows
idownerbalance
1Maya1000
2Ravi500
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23SELECT4  balance5FROM6  accounts7WHERE8  id = 19FOR UPDATE;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/9
query.sql
1UPDATE accounts2SET3  balance = balance - 5004WHERE5  id = 1;67COMMIT;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative transaction responses4 sample rows
Representative transaction responses
stepresponse
BEGINBEGIN
locked balance5000
UPDATEUPDATE 1
COMMITCOMMIT

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

A worker's loop bodyQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1UPDATE jobs2SET3  status = 'running',4  started_at = now()5WHERE6  id IN (7    SELECT8      id9    FROM10      jobs11    WHERE12      status = 'pending'13    ORDER BY14      id15    LIMIT16      1017    FOR UPDATE18      SKIP LOCKED19  )20RETURNING21  id,22  payload;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/22
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative claimed jobs2 sample rows
Representative claimed jobs
idpayload
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: NOWAIT fails fast; SKIP LOCKED turns a table into a safe work queue.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1BEGIN

Start a transaction

Row locks last until the transaction ends, so the read, the decision and the write must be inside one transaction.

SQL at this step
1BEGIN;
What to watch at this step
Lock lifetime
until COMMIT
Tip: use ← → to move between steps

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

Atomic UPDATE … WHERE condition
Best for: Simple checks: decrement if there's stock left

Strengths: No explicit lock, a single round trip.

Watch out: Only works when the check fits in the WHERE clause.

SELECT … FOR UPDATE
Best for: Decisions that need application logic between read and write

Strengths: Guarantees nobody changes the rows meanwhile.

Watch out: Others wait; long transactions cause contention and deadlocks.

FOR UPDATE SKIP LOCKED
Best for: Job queues with several workers

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?
Interview tip: Lead with the race (two transactions read the same value), fix it with an atomic UPDATE, then show FOR UPDATE for complex logic and SKIP LOCKED for queues. Three tools, one story.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Transaction Isolation Levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable)
Next topic
Table-Level Locks & Advisory Locks