Full answer
PRAGMA journal_mode = WAL;
CREATE TABLE stock (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO stock VALUES (1, 10), (2, 10);Connection A reads the level:
SELECT qty FROM stock WHERE id = 1;| qty |
|---|
| 10 |
Connection B has also read 10 and writes 11:
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;| qty |
|---|
| 11 |
Connection A, unaware, writes its own computed value 11:
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;| qty |
|---|
| 11 |
Two items were added, but the stock moved from 10 to 11. Each request was correct alone; the bug is computing the new value outside the database from a stale read.
The fix, on a second row, issues the increment as an atomic expression. Connection B first:
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;| qty |
|---|
| 11 |
Then connection A:
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;| qty |
|---|
| 12 |
Both increments land, giving 12. The database evaluates qty + 1 against the latest committed value while holding the row's write lock, so no update is lost. Where the new value needs complex logic, lock the row first or use optimistic concurrency with a version column (UPDATE ... WHERE id = ? AND version = ?, retrying when no row changes).
PRAGMA journal_mode = WAL;
CREATE TABLE stock (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO stock VALUES (1, 10), (2, 10);
SELECT qty FROM stock WHERE id = 1;
-- second session
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;
UPDATE stock SET qty = 11 WHERE id = 1;
SELECT qty FROM stock WHERE id = 1;
-- second session
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;
UPDATE stock SET qty = qty + 1 WHERE id = 2;
SELECT qty FROM stock WHERE id = 2;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Read-modify-write in code loses updates
- SET qty = qty + 1 is atomic
- SELECT ... FOR UPDATE locks before computing
- Version columns give optimistic concurrency
Common mistakes
- Computing new values from a stale read
- Assuming transactions alone prevent lost updates at every isolation level
Follow-ups
- How does a version column detect conflicts?
- Which isolation level prevents lost updates in PostgreSQL?
Tips
- Show both writes in order