Stop 12 · Transactions & ConcurrencyTopics · 6/9

Row Locks and SELECT ... FOR UPDATE

Part of the SQL Roadmap

In short

When you read a value and plan to change it, someone else can sneak in between. SELECT ... FOR UPDATE puts your hand on the row so nobody else can change it until you're done.

Databases lock rows that are being changed so two transactions cannot write the same row at once. SELECT ... FOR UPDATE locks rows you have read so no one else changes them before you update them.

At a busy fruit market stall, the jaadu rests both hands firmly on the last wooden crate of golden mangoes while two other shoppers wait beside it with outstretched arms.

Think of it like this

Hand on the last crate of mangoes

At Crawford Market there's one crate of Alphonsos left. You rest your hands on it while you count your cash. Other buyers can look at it, but they can't take it. They wait until you either pay and carry it off, or step away. FOR UPDATE is your hands on the crate.

Watch it happen

Two buyers, one item left

Session A
products row 42
Session B

SELECT stock ... FOR UPDATE

1/5A locks product 42 and reads stock = 1.

The big ideas

What you need to know

Writes lock rows

UPDATE and DELETE lock the rows they change until COMMIT or ROLLBACK. Other writers on those rows wait.

FOR UPDATE locks on read

Locks the selected rows now, so the value you read can't change before you write.

NOWAIT

Fail immediately instead of waiting if the row is already locked. Good for 'someone else is editing' messages.

SKIP LOCKED

Skips locked rows. Perfect for job queues where many workers each grab a different pending task.

See it in code

Walk through the code

sql
1BEGIN;2 3SELECT stock4FROM products5WHERE product_id = 426FOR UPDATE;              -- lock this row until COMMIT or ROLLBACK7 8-- the app checks: is stock > 0 ?9UPDATE products10SET stock = stock - 111WHERE product_id = 42;12 13INSERT INTO order_items (order_id, product_id, qty)14VALUES (8801, 42, 1);15 16COMMIT;                  -- lock released17 18-- Workers sharing a queue: each grabs a different pending job19SELECT job_id FROM jobs20WHERE status = 'pending'21ORDER BY job_id22LIMIT 123FOR UPDATE SKIP LOCKED;

1/4Inside a transaction, read the stock and lock the row in one step.

Works the same in PostgreSQL and MySQL 8. SQL Server uses table hints instead, like WITH (UPDLOCK, ROWLOCK).

Save yourself the pain

Common mistakes

Oops

Running SELECT ... FOR UPDATE without BEGIN in autocommit mode.

Do this instead

The lock is released as soon as that single statement finishes. Wrap the read and the write in one transaction.

Oops

Holding a lock while waiting for a payment gateway or user input.

Do this instead

Keep locked transactions short. Do slow work before or after, never while holding row locks.

Your mission

Stop the oversell

~25 min

Quick check

When is a lock taken by SELECT ... FOR UPDATE released?

Go deeper

  1. 1In two sessions, run SELECT ... FOR UPDATE on the same row and watch the second one wait.
  2. 2Use FOR UPDATE to safely decrease stock when two orders arrive together.
  3. 3Keep locking transactions short so other sessions are not blocked for long.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge