Database Isolation Levels
What you will learn
- What an isolation level is and why there are several
- The four levels in the SQL standard and what each allows
- What the PostgreSQL manual says about its default
- How SQLite behaves, shown with a test
1. A dial between safety and speed
Perfect isolation (every transaction behaves as if it ran alone) is safest but forces transactions to wait for each other. Databases therefore offer isolation levels, each allowing a few problems from lesson 6.4 in return for less waiting.
The SQL standard defines four levels. This table matches the one in the PostgreSQL manual (page "Transaction Isolation", opened for this lesson), including its extra column for serialization anomalies (such as write skew, section 3):
| Level | Dirty read | Non-repeatable read | Phantom read | Serialization anomaly |
|---|---|---|---|---|
| Read uncommitted | possible | possible | possible | possible |
| Read committed | not possible | possible | possible | possible |
| Repeatable read | not possible | not possible | possible (the standard allows it) | possible |
| Serializable | not possible | not possible | not possible | not possible |
"Serializable" means the result is the same as if the transactions had run one after another in some order. The PostgreSQL manual defines a serialization anomaly as a result of committing a group of transactions that is inconsistent with all possible orderings of running them one at a time.
Real databases do not all follow the table exactly. The same PostgreSQL manual says that in PostgreSQL you can request any of the four levels, that Read Committed is the default, that its Read Uncommitted level behaves like Read Committed (it never shows dirty reads), and that its Repeatable Read is built on snapshots and does not show phantom reads. The MySQL manual says its InnoDB engine supports all four levels and that its default is Repeatable Read. So two popular products have different defaults, and you must read the manual of the database you use before relying on a level.
Snapshots and MVCC in plain words. Most modern databases avoid making readers wait by keeping several versions of a row. A reader works from a snapshot, a picture of the data as it was at one moment, while writers create new versions. This is called multiversion concurrency control (MVCC). The PostgreSQL manual's introduction to it says each statement sees a snapshot of the data at some point in time, and that for this reason reading does not block writing and writing does not block reading. The WAL test in section 2 shows the idea in SQLite: B keeps reading 10 even after A has written 7.
You choose a level per transaction in databases that support it. In PostgreSQL the syntax starts a transaction like this: BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;. SQLite has no such command for choosing between the four levels; it behaves as described next.
2. How SQLite behaves
SQLite's own page on isolation says its transactions are serializable. It gets there by allowing only one writer at a time, rather than by juggling many writers. The tests below use two connections to a file database (stock table, pen quantity 10). Setup (the same as in lesson 6.4, so this lesson runs on its own):
import sqlite3, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "shop.db")
a = sqlite3.connect(path, timeout=0.2, isolation_level=None)
b = sqlite3.connect(path, timeout=0.2, isolation_level=None)
a.execute("CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL)")
a.execute("INSERT INTO stock VALUES ('pen', 10)")
Test 1: a reader holds its view. B begins a transaction and reads. A then tries to change the row:
b.execute("BEGIN")
print("B first read:", b.execute("SELECT qty FROM stock").fetchone()[0])
try:
a.execute("UPDATE stock SET qty = 7")
except sqlite3.OperationalError as e:
print("A:", e)
b.execute("COMMIT")
B first read: 10
A: database is locked
In SQLite's default (rollback-journal) mode, B's open read stops A from changing the data. B can never see a change halfway through its transaction, because none is allowed to happen. A must wait (here it gave up after 0.2 seconds).
Test 2: WAL mode. SQLite also has a write-ahead log mode that lets readers and a writer work together:
a.execute("PRAGMA journal_mode=WAL")
b.execute("BEGIN")
print("B first read:", b.execute("SELECT qty FROM stock").fetchone()[0])
a.execute("UPDATE stock SET qty = 7")
print("B second read (WAL):", b.execute("SELECT qty FROM stock").fetchone()[0])
b.execute("COMMIT")
print("B after commit:", b.execute("SELECT qty FROM stock").fetchone()[0])
B first read: 10
B second read (WAL): 10
B after commit: 7
Now A's change went through, yet B kept seeing the snapshot it started with (10) until its transaction ended, then saw 7. That gives B repeatable reads without blocking A.
A reader with an old snapshot cannot then turn into a writer on stale data:
b.execute("BEGIN")
b.execute("SELECT qty FROM stock").fetchone()
a.execute("UPDATE stock SET qty = 5")
try:
b.execute("UPDATE stock SET qty = 1")
except sqlite3.OperationalError as e:
print("B write error:", e)
b.execute("ROLLBACK")
B write error: database is locked
B read, someone else changed the row, and B's write is refused rather than overwriting data B never saw. B must roll back and start again.
3. Write skew: the problem snapshots do not solve
Snapshots stop you seeing half-finished work, but a snapshot can be stale by the time you write. The classic story: a hospital rule says at least one doctor must stay on call. Two doctors both check, both see 2 on call, and each goes off call:
| Time | Transaction A (Dr Ali) | Transaction B (Dr Bela) |
|---|---|---|
| 1 | reads: 2 on call | reads: 2 on call |
| 2 | sets Ali off call | |
| 3 | commits | sets Bela off call |
| 4 | commits: now 0 on call |
Neither transaction changed a row the other changed, so a snapshot-based level with no extra checks can accept both. A database that offers true Serializable must detect this and refuse one transaction (the PostgreSQL manual lists serialization anomalies as impossible at Serializable). SQLite, being serializable, refuses the second write:
import sqlite3, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "hospital.db")
a = sqlite3.connect(path, timeout=0.2, isolation_level=None)
b = sqlite3.connect(path, timeout=0.2, isolation_level=None)
a.execute("PRAGMA journal_mode=WAL")
a.execute("CREATE TABLE doctors (name TEXT PRIMARY KEY, on_call INTEGER NOT NULL)")
a.execute("INSERT INTO doctors VALUES ('Dr Ali',1),('Dr Bela',1)")
rule = "SELECT COUNT(*) FROM doctors WHERE on_call=1"
a.execute("BEGIN"); b.execute("BEGIN")
print("A sees on call:", a.execute(rule).fetchone()[0], "| B sees on call:", b.execute(rule).fetchone()[0])
a.execute("UPDATE doctors SET on_call=0 WHERE name='Dr Ali'")
a.execute("COMMIT")
try:
b.execute("UPDATE doctors SET on_call=0 WHERE name='Dr Bela'")
b.execute("COMMIT")
except sqlite3.OperationalError as e:
print("B refused:", e); b.execute("ROLLBACK")
print("on call at the end:", a.execute(rule).fetchone()[0])
A sees on call: 2 | B sees on call: 2
B refused: database is locked
on call at the end: 1
B's write was refused because B's snapshot was out of date, so the rule "at least one on call" still holds. In a database at a lower level you would have to protect such a rule yourself: lock the rows you read, put the rule in a constraint where possible, or retry on conflict (lessons 6.6 to 6.8).
Write skew and its guard in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A SQL cell has one connection, so the cells play both doctors one after the other, each acting on the number they saw (2). The table is a small one of its own; Reset data starts again.
CREATE TABLE doctors (name TEXT PRIMARY KEY, on_call INTEGER NOT NULL);
INSERT INTO doctors VALUES ('Dr Ali', 1), ('Dr Bela', 1);
SELECT COUNT(*) AS on_call FROM doctors WHERE on_call = 1;
on_call
-------
2
(1 row)
Both doctors saw 2, so each goes off call. Neither statement touches the other's row, and nothing is refused:
UPDATE doctors SET on_call = 0 WHERE name = 'Dr Ali';
UPDATE doctors SET on_call = 0 WHERE name = 'Dr Bela';
SELECT COUNT(*) AS on_call FROM doctors WHERE on_call = 1;
on_call
-------
0
(1 row)
The rule "at least one on call" is broken. A guard puts the rule check inside the write, so the check and the change happen together:
UPDATE doctors SET on_call = 1;
UPDATE doctors SET on_call = 0
WHERE name = 'Dr Ali' AND (SELECT COUNT(*) FROM doctors WHERE on_call = 1) > 1;
UPDATE doctors SET on_call = 0
WHERE name = 'Dr Bela' AND (SELECT COUNT(*) FROM doctors WHERE on_call = 1) > 1;
SELECT name, on_call FROM doctors ORDER BY name;
name on_call
------- -------
Dr Ali 0
Dr Bela 1
(2 rows)
CREATE TABLE doctors (name TEXT PRIMARY KEY, on_call INTEGER NOT NULL);
INSERT INTO doctors VALUES ('Dr Ali', 1), ('Dr Bela', 1);
SELECT COUNT(*) AS on_call FROM doctors WHERE on_call = 1;
on_call
-------
2
(1 row)
Both doctors saw 2, so each goes off call. Neither statement touches the other's row, and nothing is refused:
UPDATE doctors SET on_call = 0 WHERE name = 'Dr Ali';
UPDATE doctors SET on_call = 0 WHERE name = 'Dr Bela';
SELECT COUNT(*) AS on_call FROM doctors WHERE on_call = 1;
on_call
-------
0
(1 row)
The rule "at least one on call" is broken. A guard puts the rule check inside the write, so the check and the change happen together:
UPDATE doctors SET on_call = 1;
UPDATE doctors SET on_call = 0
WHERE name = 'Dr Ali' AND (SELECT COUNT(*) FROM doctors WHERE on_call = 1) > 1;
UPDATE doctors SET on_call = 0
WHERE name = 'Dr Bela' AND (SELECT COUNT(*) FROM doctors WHERE on_call = 1) > 1;
SELECT name, on_call FROM doctors ORDER BY name;
name on_call
------- -------
Dr Ali 0
Dr Bela 1
(2 rows)
CREATE TABLE doctors (name TEXT PRIMARY KEY, on_call INTEGER NOT NULL);
INSERT INTO doctors VALUES ('Dr Ali', 1), ('Dr Bela', 1);
SELECT COUNT(*) AS on_call FROM doctors WHERE on_call = 1;
on_call
-------
2
(1 row)
Both doctors saw 2, so each goes off call. Neither statement touches the other's row, and nothing is refused:
UPDATE doctors SET on_call = 0 WHERE name = 'Dr Ali';
UPDATE doctors SET on_call = 0 WHERE name = 'Dr Bela';
SELECT COUNT(*) AS on_call FROM doctors WHERE on_call = 1;
on_call
-------
0
(1 row)
The rule "at least one on call" is broken. A guard puts the rule check inside the write, so the check and the change happen together:
UPDATE doctors SET on_call = 1;
UPDATE doctors SET on_call = 0
WHERE name = 'Dr Ali' AND (SELECT COUNT(*) FROM doctors WHERE on_call = 1) > 1;
UPDATE doctors SET on_call = 0
WHERE name = 'Dr Bela' AND (SELECT COUNT(*) FROM doctors WHERE on_call = 1) > 1;
SELECT name, on_call FROM doctors ORDER BY name;
name on_call
------- -------
Dr Ali 0
Dr Bela 1
(2 rows)
The second update changed no row (the program sees 0 rows changed and tells Dr Bela to stay on call), so one doctor remains. Whether such a guarded statement is safe against a truly simultaneous second transaction depends on the database and its level; in SQLite, with only one writer at a time, it is.
Worked example: choosing a level
| Job | What it needs | Reasonable choice |
|---|---|---|
| Show a product page | a recent value; slight staleness is fine | a lower level such as Read committed |
| Print a month-end report that reads many tables | the same data in every query | Repeatable read or Serializable, or a snapshot |
| Transfer money between accounts | no overlap damage at all | Serializable, or careful locking |
Higher levels cost more waiting or more retries. Choose the lowest level that is still correct for the job, and test it. The jobs are made up.
Common mistakes
- Assuming the level names mean the same in every database. Check the manual.
- Choosing Serializable everywhere "to be safe" without handling the retries it may cause.
- Assuming the default is enough for money or stock logic.
- Forgetting that SQLite's behaviour depends on its journal mode (rollback journal or WAL).
Key takeaways
- Isolation levels trade safety against waiting.
- The standard levels are Read uncommitted, Read committed, Repeatable read and Serializable.
- PostgreSQL's manual names Read Committed as its default; MySQL's InnoDB default is Repeatable Read.
- Snapshots (MVCC) let readers and writers work together, but write skew needs Serializable, locks or a retry.
- SQLite is serializable: one writer at a time, and in WAL mode readers keep a snapshot.
- A write based on stale data can be refused; the program must retry.
Practice
1. Which problems does Read committed still allow, per the standard table?
Show answer
Non-repeatable reads and phantom reads (but not dirty reads).
2. What does "serializable" mean?
Show answer
The outcome is the same as if the transactions had run one after another in some order.
3. What are the default levels of PostgreSQL and of MySQL's InnoDB, according to their manuals?
Show answer
PostgreSQL: Read Committed. InnoDB: Repeatable Read.
4. In the WAL test, why did B's second read still show 10?
Show answer
B was working from the snapshot taken when its transaction started; it only saw the committed 7 after its own transaction ended.
5. Why might a database refuse a write after your read?
Show answer
Someone changed the row after your snapshot, and writing now would overwrite data you never saw. Your program should roll back and retry.
6. Two doctors each read "2 on call" and each go off call. Which problem is this, and which of the four levels is guaranteed to stop it?
Show answer
Write skew (a serialization anomaly). Only Serializable is guaranteed to prevent it; the lower levels may allow it. Databases also differ in how they implement the levels, which is why you must check the manual of your own product.