Engineers who move between PostgreSQL and MySQL often assume that a level with the same name behaves the same way. It does not, and the defaults differ too: PostgreSQL starts every transaction at READ COMMITTED, MySQL's InnoDB at REPEATABLE READ. Code that is correct on one engine can lose updates on the other.
Rather than repeat the SQL standard's table, I ran four concrete tests on both engines, each in two terminal sessions, and recorded what happened. Versions: PostgreSQL 16.4 and MySQL 8.0.39, default configuration.
Setup
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 'ana', 100), (2, 'ben', 100);
CREATE TABLE on_call (doctor text PRIMARY KEY, on_duty boolean NOT NULL);
INSERT INTO on_call VALUES ('alice', true), ('bob', true);
(For MySQL, owner and doctor are VARCHAR(50).) Each test uses session A and session B. Steps are
numbered in the order they run.
Test 1: non-repeatable read
Does a transaction see a value change if it reads the same row twice?
-- A1
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- 100
-- B1
UPDATE accounts SET balance = 50 WHERE id = 1; -- autocommit
-- A2
SELECT balance FROM accounts WHERE id = 1; -- ?
COMMIT;
- PostgreSQL READ COMMITTED: A2 returns 50. Each statement takes a fresh snapshot.
- MySQL REPEATABLE READ: A2 returns 100. The first read established a snapshot for the whole transaction.
Test 2: phantom rows
Does a repeated range query see newly inserted rows?
-- A1
BEGIN;
SELECT count(*) FROM accounts WHERE balance >= 50; -- 2
-- B1
INSERT INTO accounts VALUES (3, 'cy', 70);
-- A2
SELECT count(*) FROM accounts WHERE balance >= 50; -- ?
COMMIT;
- PostgreSQL READ COMMITTED: 3.
- MySQL REPEATABLE READ: 2, for a plain
SELECT. But there is a twist, below.
The MySQL twist: snapshot reads and current reads
In InnoDB, plain SELECT reads from the transaction's snapshot. UPDATE, DELETE and locking reads
(SELECT ... FOR UPDATE) read the latest committed rows. Continuing test 2 inside the same
transaction:
-- A3 (MySQL, same transaction as A1/A2)
UPDATE accounts SET balance = balance + 1 WHERE balance >= 50;
-- Query OK, 3 rows affected
SELECT count(*) FROM accounts WHERE balance >= 50; -- now 3
The update touched three rows, including one the transaction could not see a moment earlier, and after updating it, the transaction sees it. The MySQL manual describes this behaviour. It surprises people who expect REPEATABLE READ to mean "my transaction sees a frozen world".
PostgreSQL REPEATABLE READ does not mix the two: an UPDATE there works on the snapshot and, if a target
row was changed by a concurrent committed transaction, fails with a serialization error instead.
Test 3: lost update (read, modify, write in the application)
The most practical test. Two requests each read a balance, add to it in application code, and write it back.
-- A1
BEGIN;
SELECT balance FROM accounts WHERE id = 2; -- 100, app computes 100 + 10
-- B1
BEGIN;
SELECT balance FROM accounts WHERE id = 2; -- 100, app computes 100 + 20
-- A2
UPDATE accounts SET balance = 110 WHERE id = 2;
COMMIT;
-- B2
UPDATE accounts SET balance = 120 WHERE id = 2; -- ?
COMMIT;
-- final balance?
- PostgreSQL READ COMMITTED: B2 succeeds, final balance 120. A's +10 is lost.
- MySQL REPEATABLE READ: B2 succeeds, final balance 120. Lost as well.
- PostgreSQL REPEATABLE READ: B2 fails with
ERROR: could not serialize access due to concurrent update. The application must retry, and the retry reads 110 and writes 130.
So MySQL's stronger-sounding default does not prevent lost updates from application-side read-modify-write. PostgreSQL's REPEATABLE READ does, by raising an error.
Note what does not lose updates on any of these levels: doing the arithmetic in SQL.
UPDATE accounts SET balance = balance + 10 WHERE id = 2 takes the row lock and re-reads the latest
value, on both engines. Neither is it lost with SELECT ... FOR UPDATE before the read.
Test 4: write skew
Two transactions each check a condition across rows and update a different row. Rule: at least one doctor must stay on duty.
-- A1
BEGIN;
SELECT count(*) FROM on_call WHERE on_duty; -- 2, so alice may leave
-- B1
BEGIN;
SELECT count(*) FROM on_call WHERE on_duty; -- 2, so bob may leave
-- A2
UPDATE on_call SET on_duty = false WHERE doctor = 'alice';
COMMIT;
-- B2
UPDATE on_call SET on_duty = false WHERE doctor = 'bob';
COMMIT;
- PostgreSQL READ COMMITTED: both commit. Nobody is on duty.
- MySQL REPEATABLE READ: both commit. Same result.
- PostgreSQL REPEATABLE READ: both commit. Snapshot isolation does not prevent write skew, because the two transactions update different rows.
- PostgreSQL SERIALIZABLE: the second commit fails with
ERROR: could not serialize access due to read/write dependencies among transactions. - MySQL SERIALIZABLE: plain
SELECTbecomes a shared-locking read. Each session's update waits on the other's shared locks, and InnoDB resolves the cycle withERROR 1213 (40001): Deadlock found when trying to get lock.
Results
| Test | PG READ COMMITTED (default) | PG REPEATABLE READ | PG SERIALIZABLE | MySQL READ COMMITTED | MySQL REPEATABLE READ (default) | MySQL SERIALIZABLE |
|---|---|---|---|---|---|---|
| Non-repeatable read | happens | prevented | prevented | happens | prevented (plain SELECT) | prevented |
| Phantom (plain SELECT) | happens | prevented | prevented | happens | prevented, but UPDATE sees new rows | prevented (locks) |
| Lost update, app-side | lost | error, retry | error, retry | lost | lost | deadlock error, retry |
| Write skew | allowed | allowed | error, retry | allowed | allowed | deadlock error, retry |
How we choose a level
The table makes one thing clear: no default protects you from the two anomalies that cause real bugs, lost updates and write skew. Choosing a level is less about the global setting and more about each piece of code that reads and then writes.
Our guidelines, per transaction:
- Prefer statements that are safe on any level.
UPDATE ... SET x = x + ?, conditional updates likeUPDATE ... WHERE balance >= ?with a row-count check, and unique constraints solve most cases without thinking about isolation. - For read-then-write on specific rows, lock what you read.
SELECT ... FOR UPDATEworks the same way on both engines and on any level. - For rules across several rows (write skew), lock or materialise the rule. Either lock all the rows
the rule depends on (
FOR UPDATEon the whole on-call set), or keep the constraint in one row that every writer updates, such as a counter on the shift. - Use SERIALIZABLE when the logic is complex and you cannot easily list what to lock. On PostgreSQL
this is real serializable snapshot isolation and performs well for many workloads. It requires retry
logic for SQLSTATE
40001on every transaction, which is the actual cost. - Keep the default for everything else, and know which default you are on.
For applications that run on both engines (we have one), we set the level explicitly at connection start, so behaviour does not depend on which database the code runs against:
-- PostgreSQL
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- MySQL
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
We chose READ COMMITTED on both, with explicit locking where needed, because it makes MySQL's behaviour match PostgreSQL's for the tests above and removes the snapshot-versus-current-read surprise.
Retrying correctly
Any level that raises serialization errors needs a retry wrapper that re-runs the whole transaction, including the reads, not just the failing statement:
def run_serializable(fn, attempts=5):
for i in range(attempts):
try:
with db.transaction(isolation="serializable"):
return fn()
except SerializationFailure: # SQLSTATE 40001 (and 40P01 for deadlocks)
time.sleep(0.01 * 2 ** i * random.random())
raise RuntimeError("transaction kept conflicting")
Retrying only the last UPDATE would reuse stale values read earlier and reintroduce the anomaly.
Summary
- PostgreSQL defaults to READ COMMITTED; MySQL InnoDB to REPEATABLE READ. Same names, different behaviour.
- MySQL REPEATABLE READ snapshots plain reads but
UPDATEsees the latest rows, and it still loses app-side read-modify-write updates. - PostgreSQL REPEATABLE READ turns lost updates into errors; only SERIALIZABLE prevents write skew.
- Prefer atomic SQL,
FOR UPDATEand constraints; use SERIALIZABLE with full-transaction retries when the logic is too complex to lock by hand.
References: PostgreSQL transaction isolation, MySQL InnoDB transaction isolation levels, MySQL consistent nonlocking reads.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.