Sub topic 8
Lost updates and how to prevent them
This chapter assumes you know basic SQL, can use BEGIN, COMMIT and ROLLBACK, and have read the earlier chapters on dirty reads, non-repeatable reads and the SQL standard isolation levels. Here you will see how one common anomaly, the lost update, happens and which techniques stop it.
What a lost update is
A lost update happens when two transactions read the same value, each computes a new value from what it read, and each writes its result back. The second write replaces the first, so the first change disappears. Neither transaction fails and neither sees an error.
The pattern behind it is called read-modify-write. Typical examples are:
- Adding a deposit to an account balance.
- Decrementing a stock counter.
- Editing a record in a web form and saving the whole row.
- Appending an item to a JSON document that the application read earlier.
The anomaly is easiest to see on a timeline.
Session A meant to deposit 10 and session B meant to deposit 20. The correct result is 130. The database ends at 120.
Reproducing it
Create the table and run the two sessions step by step in two terminals.
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
-- Session A -- Session B
BEGIN; BEGIN;
SELECT balance FROM accounts WHERE id = 1; SELECT balance FROM accounts WHERE id = 1;
-- 100 -- 100
-- The application computes 100 + 10 -- The application computes 100 + 20
UPDATE accounts SET balance = 110
WHERE id = 1;
COMMIT;
UPDATE accounts SET balance = 120
WHERE id = 1;
COMMIT;
SELECT balance FROM accounts WHERE id = 1;
-- 120, not 130This runs without error under READ COMMITTED in PostgreSQL, the default level. Session B's UPDATE waits only if A still holds the row lock. Once A commits, B overwrites the row with a value that was computed from stale data.
Which isolation levels allow it
The SQL standard does not list lost updates as a separate anomaly. The result depends on the level and on the engine.
| Level and engine | Lost update possible? |
|---|---|
| READ UNCOMMITTED | Yes |
| READ COMMITTED (PostgreSQL, SQL Server, Oracle) | Yes, for read-modify-write in application code |
| REPEATABLE READ in PostgreSQL | No. The second writer fails with a serialization error |
| REPEATABLE READ in MySQL InnoDB | Yes for plain read-then-write. The `UPDATE` re-reads the latest committed row, so the writer does not detect the conflict |
| SERIALIZABLE | No, in every engine that implements it correctly |
The InnoDB row needs care. In InnoDB, a plain SELECT reads from the snapshot, but an UPDATE operates on the latest committed version of the row. If your application computed the new value from the snapshot read, the write still goes through and the earlier change is lost. Do not rely on REPEATABLE READ alone in MySQL.
PostgreSQL behaves differently. Under REPEATABLE READ, if a transaction tries to update a row that another transaction changed and committed after the first one's snapshot was taken, PostgreSQL aborts it. You then retry the whole transaction.
-- PostgreSQL, Session B, after Session A has committed its change
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- ... Session A updates and commits here ...
UPDATE accounts SET balance = 120 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update
ROLLBACK;The error has SQLSTATE 40001. The application must catch it and run the transaction again, as covered in the chapter on conflict handling.
Prevention techniques
There are five common ways to stop lost updates. They differ in cost and in where the safety check lives.
Atomic update expressions
The simplest fix is to let the database do the arithmetic in a single statement.
UPDATE accounts SET balance = balance + 10 WHERE id = 1;The statement reads and writes the row under one row lock. A concurrent writer waits until the first commits, then applies its own change to the new value. Both deposits survive and the balance becomes 130.
Use this whenever the new value is a function of the old value that SQL can express. It works at READ COMMITTED in PostgreSQL, MySQL, SQL Server and Oracle, needs no retry logic and adds almost no overhead.
Pessimistic locking with SELECT ... FOR UPDATE
If the application must read the value and apply logic that SQL cannot express, lock the row when you read it.
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- The application computes the new value, for example 110
UPDATE accounts SET balance = 110 WHERE id = 1;
COMMIT;FOR UPDATE takes an exclusive row lock. A second transaction that runs the same SELECT ... FOR UPDATE blocks until the first commits or rolls back. It then reads the new value, so it computes from fresh data.
The lock is held until the end of the transaction. Keep the transaction short, and never hold it open while waiting for a user or a remote service. On SQL Server, the equivalent hint is WITH (UPDLOCK, ROWLOCK). Oracle supports SELECT ... FOR UPDATE with the same meaning.
Optimistic concurrency with a version column
Optimistic concurrency takes no lock at read time. Instead, each row carries a version number, and the write succeeds only if the version has not changed.
ALTER TABLE accounts ADD COLUMN version int NOT NULL DEFAULT 0;
-- Application reads: balance = 100, version = 0
UPDATE accounts
SET balance = 110, version = version + 1
WHERE id = 1 AND version = 0;
-- The driver reports "1 row updated" on success, "0 rows updated" on conflict.If another transaction changed the row first, its version is now 1, the WHERE clause matches nothing, and the statement reports zero rows. The application sees the zero, re-reads the row and tries again, or reports the conflict to the user.
This approach suits long interactions such as an edit form that stays open for minutes. No database lock is held while the user thinks. The cost is that the application must check the row count and handle the failure. ORMs such as Hibernate and Django offer this as a built-in feature.
Compare-and-set on the value itself
A variant uses the old value as the condition, with no extra column.
UPDATE accounts SET balance = 110 WHERE id = 1 AND balance = 100;This is simple, but it cannot distinguish "unchanged" from "changed and changed back" (the ABA problem). For counters that never return to an old value, it is fine. For anything else, prefer a version column.
Higher isolation levels
A third route is to let the database detect the conflict.
- PostgreSQL REPEATABLE READ and SERIALIZABLE abort the later writer, as shown earlier.
- SQL Server SNAPSHOT isolation does the same and raises error 3960 on a write conflict.
- Oracle SERIALIZABLE raises
ORA-08177: can't serialize access for this transaction. - MySQL InnoDB SERIALIZABLE turns plain reads into locking reads, so the two sessions block each other. A deadlock can occur, in which case one session is rolled back.
In all cases the application must be ready to retry.
Comparing the techniques
| Technique | Where the check happens | Blocks other writers? | Needs retry? | Best for |
|---|---|---|---|---|
| Atomic `UPDATE` expression | Inside one statement | Briefly, for the row lock | No | Counters, balances, increments |
| `SELECT ... FOR UPDATE` | Lock taken at read time | Yes, until commit | No, but watch for deadlocks | Short read-then-decide logic |
| Version column | In the `WHERE` clause | No | Yes | Long interactions, ORMs |
| Compare-and-set on value | In the `WHERE` clause | No | Yes | Simple counters |
| Repeatable read or serializable | Engine detects the conflict | Depends on engine | Yes | When many code paths touch the data |
Edge cases and gotchas
- Several rows involved. A lost update is defined on a single row. If your rule spans several rows (for example, at least one doctor on duty), locking one row does not help. That is write skew, covered in a later chapter.
- Lock ordering. If two transactions lock rows
1and2in opposite orders withFOR UPDATE, they deadlock. Always lock rows in a consistent order, such as ascending primary key. - Triggers and defaults. A column default or trigger that reads other rows can reintroduce stale reads even when the main
UPDATEis atomic. - Caches. A value read from an application cache and written back to the database is a read-modify-write that the database cannot protect. Use a version check or move the arithmetic into SQL.
- Autocommit. In autocommit mode, each statement is its own transaction. Read and write are then separate transactions, and
FOR UPDATEhas no lasting effect because the lock is released immediately. Open an explicit transaction. - Row counts. Optimistic checks only work if your code looks at the affected-row count. Ignoring it silently loses the update.
Choosing a technique
- If the change is an expression of the old value, use an atomic
UPDATE. - If you must read, decide in code and write within a short transaction, use
SELECT ... FOR UPDATE. - If the user may hold the data for a long time, use a version column.
- If many code paths touch the same data and you cannot audit them all, raise the isolation level and add retries.
Exercise
Two sessions run SELECT balance (100), and then Session A writes 110 and commits, and Session B writes 120 and commits, all under READ COMMITTED. What is the final balance, and give two different changes to the application code that make the final balance 130?
Show answer
The final balance is 120, because B overwrites A's write with a value computed from the stale read. Fix 1: replace the read-modify-write with UPDATE accounts SET balance = balance + 10 WHERE id = 1; (and + 20 in B), so the database applies each change to the current value. Fix 2: in each transaction, read with SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; so that the second session blocks until the first commits and then reads 110 before computing 130. A version column with a retry on zero updated rows also works.
Exercise
In MySQL InnoDB at REPEATABLE READ, a transaction reads a balance with a plain SELECT, computes a new value in the application, and then runs UPDATE. Another transaction committed a change to that row in between. Is the other change lost, and why?
Show answer
Yes. A plain SELECT reads from the transaction's snapshot, but an UPDATE works on the latest committed version of the row and does not raise a conflict error. The write replaces the other transaction's change with a value computed from the older snapshot. Use an atomic expression, SELECT ... FOR UPDATE (a locking read, which also reads the latest version), or a version column.