← Back to SQL, page 12

sql-0230 · Medium mid

Two users each read a stock count of 5, subtract 1 in application code, and write back 4. What went wrong, and how do you fix it?

This is a lost update: both read the same value, both wrote a result based on it, and one decrement vanished. Fix it with an atomic UPDATE that computes in the database (SET qty = qty - 1 WHERE qty > 0), with SELECT ... FOR UPDATE to lock the row before reading, or with optimistic concurrency using a version column.

Full answer

The broken pattern:

text
A: SELECT qty FROM stock WHERE sku = 'pen';   -- 5
B: SELECT qty FROM stock WHERE sku = 'pen';   -- 5
A: UPDATE stock SET qty = 4 WHERE sku = 'pen';
B: UPDATE stock SET qty = 4 WHERE sku = 'pen';  -- should be 3

The atomic version leaves no gap between read and write, and the WHERE stops overselling:

sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 1);
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
SELECT qty FROM stock;
qty
0

Optimistic concurrency checks that nobody changed the row since it was read. If the version moved on, zero rows change and the application retries:

sql
CREATE TABLE doc (id INTEGER PRIMARY KEY, body TEXT, version INTEGER NOT NULL);
INSERT INTO doc VALUES (1, 'v1 text', 1);
UPDATE doc SET body = 'edit by A', version = version + 1 WHERE id = 1 AND version = 1;
UPDATE doc SET body = 'edit by B', version = version + 1 WHERE id = 1 AND version = 1;
SELECT body, version, changes() AS rows_changed_by_last_update FROM doc;
bodyversionrows_changed_by_last_update
edit by A20

On PostgreSQL, SELECT ... FOR UPDATE inside a transaction makes the second reader wait for the first to finish. REPEATABLE READ in PostgreSQL also detects this conflict and fails the second transaction with a serialization error, which the application must retry (not run as a concurrent session here).

sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 1);
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
UPDATE stock SET qty = qty - 1 WHERE sku = 'pen' AND qty > 0;
SELECT qty FROM stock;

CREATE TABLE doc (id INTEGER PRIMARY KEY, body TEXT, version INTEGER NOT NULL);
INSERT INTO doc VALUES (1, 'v1 text', 1);
UPDATE doc SET body = 'edit by A', version = version + 1 WHERE id = 1 AND version = 1;
UPDATE doc SET body = 'edit by B', version = version + 1 WHERE id = 1 AND version = 1;
SELECT body, version, changes() AS rows_changed_by_last_update FROM doc;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Lost update: concurrent read-modify-write cycles overwrite each other
  • Compute in the UPDATE itself when possible
  • SELECT ... FOR UPDATE locks the row before reading
  • Version columns give optimistic concurrency

Common mistakes

  • Computing new values in application code from a stale read
  • Ignoring the zero-rows-updated result of an optimistic update

Follow-ups

  • When is optimistic locking better than FOR UPDATE?
  • How would you reserve stock for a cart for 10 minutes?

Tips

  • Write the two-session timeline