Sub topic 6
The four SQL standard isolation levels
This chapter assumes you can write basic SQL, use BEGIN, COMMIT and ROLLBACK, and know that a database serves many clients at once. You should also know the three read anomalies from the previous chapters: dirty reads, non-repeatable reads and phantom reads.
Why the standard defines levels
Full isolation makes concurrent transactions behave as if they ran one after another. That is the safest behavior, but it costs concurrency. The database must make transactions wait for each other, or abort some of them. Many workloads do not need that guarantee, so the SQL standard defines four isolation levels. Each level is a point on a scale between safety and throughput.
The standard defines each level by the read anomalies it forbids. Moving up a level forbids more anomalies and usually costs more waiting or more retries.
The four levels
From weakest to strongest, the levels are:
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
READ UNCOMMITTED
A transaction at this level may see changes that other transactions have not yet committed. If that other transaction rolls back, you have read data that never officially existed. This is a dirty read.
The level is rarely useful. It can serve rough estimates on huge tables, where an approximate answer is acceptable and you want to avoid any waiting. Be aware that several engines do not implement it as written. PostgreSQL treats it as READ COMMITTED.
READ COMMITTED
Each statement sees only data that was committed before that statement began. Dirty reads are impossible. Two statements in the same transaction can still see different data, because other transactions may commit between them.
This is the default in PostgreSQL, Oracle and SQL Server. Here is how a non-repeatable read looks:
-- Setup: CREATE TABLE accounts (id int PRIMARY KEY, balance int);
-- INSERT INTO accounts VALUES (1, 100);
-- Session A (READ COMMITTED)
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- returns 100
-- Session B
BEGIN;
UPDATE accounts SET balance = 50 WHERE id = 1;
COMMIT;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- returns 50
COMMIT;Session A read the same row twice and got two answers. At READ COMMITTED this is allowed.
REPEATABLE READ
Once a transaction has read a row, it sees the same value for that row for the rest of the transaction. Dirty reads and non-repeatable reads are both forbidden.
The standard still permits phantom reads at this level. A phantom happens when you run the same range query twice and the second run returns extra rows that another transaction inserted and committed. Many engines go beyond the standard here, as the next sections show.
If you repeat the example above with BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ in Session A, the second SELECT still returns 100.
SERIALIZABLE
The strongest level. The result of running transactions concurrently must be the same as running them one at a time in some order. All the read anomalies are forbidden, including phantoms.
The standard's wording is about outcomes, not mechanisms. An engine may reach this guarantee with locks, with conflict detection, or with a mix. In every case, you should expect some transactions to wait or to be aborted.
The anomaly matrix
This table shows which anomalies the standard permits at each level.
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Not possible | Possible | Possible |
| REPEATABLE READ | Not possible | Not possible | Possible |
| SERIALIZABLE | Not possible | Not possible | Not possible |
The table is a minimum. The standard says a level must not show anomalies marked "Not possible". It does not say that anomalies marked "Possible" must occur. An engine may give more protection than the standard requires, and most do.
What the table leaves out
The standard's table lists only three anomalies. Two important problems are missing from it, and they cause real bugs.
- Lost updates. Two transactions read a value, then each writes a new value based on what it read. One write overwrites the other. Depending on the engine, this can happen at
READ COMMITTED, and in some engines it can happen atREPEATABLE READ. - Write skew. Two transactions read overlapping data, then each updates a different row. Each update is valid alone, but together they break a rule. Snapshot-based engines can allow this at their
REPEATABLE READlevel.
A level's name therefore does not tell you whether your application is safe. Only SERIALIZABLE rules out every anomaly, and even that depends on the engine implementing it properly. Later chapters cover lost updates, write skew and the engine differences in detail.
Setting the level
You choose the level per transaction. The syntax differs between engines.
-- PostgreSQL: choose the level when the transaction starts
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- ... more statements ...
COMMIT;
-- MySQL: applies to the next transaction in this session
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
SELECT balance FROM accounts WHERE id = 1;
COMMIT;In PostgreSQL the level must be set before the first query of the transaction. In MySQL, SET TRANSACTION without a keyword such as SESSION affects only the next transaction. The next chapter covers setting levels in more detail.
Cost of each level
Higher levels do not make queries slower on their own. The cost comes from how the engine enforces the guarantee.
| Level | Typical cost |
|---|---|
| READ UNCOMMITTED | Almost none, but the data may be wrong |
| READ COMMITTED | Low. Each statement takes a fresh view of committed data |
| REPEATABLE READ | A held snapshot or held read locks. Long transactions keep old row versions alive, or block writers |
| SERIALIZABLE | Extra tracking of reads and writes. Some transactions fail and must be retried, or they wait on locks |
When a lock-based engine raises the level, the cost shows up as waiting. When a snapshot-based engine raises it, the cost shows up as aborted transactions. In both cases the application must be prepared for the consequences. At SERIALIZABLE in PostgreSQL, your code must be ready to retry a transaction that fails with SQLSTATE 40001.
Common errors
- Believing the name over the engine. Code that works at
REPEATABLE READin one engine may fail in another. - Raising the level without adding retries. A higher level can produce serialization failures that the lower level never did. If the application does not retry, users see errors.
- Mixing levels carelessly. The weakest transaction in a workflow can undermine a rule that stronger transactions protect, because isolation applies only between transactions that share a guarantee.
- Holding transactions open. Long transactions at
REPEATABLE READor above keep snapshots or locks for a long time, so they hurt other sessions. - Treating
READ UNCOMMITTEDas a performance switch. In engines that implement it, it trades correctness for little gain. In others, it is silently upgraded.
Summary
The four standard levels form a ladder. Each rung forbids one more read anomaly. The standard's table covers dirty reads, non-repeatable reads and phantoms, but real applications also face lost updates and write skew, which the table does not cover. Engines implement the levels in different ways, so you must check the exact behavior of the engine you use.
Exercise
A transaction runs SELECT count(*) FROM orders WHERE status = 'open' twice. Between the two queries, another transaction inserts a new open order and commits. The second query returns a larger count. Which anomaly is this, and which standard levels permit it?
Show answer
This is a phantom read, because a new row now matches the same range condition. The standard permits it at READ UNCOMMITTED, READ COMMITTED and REPEATABLE READ. Only SERIALIZABLE forbids it. Some engines, such as PostgreSQL at REPEATABLE READ, give more protection than the standard requires and prevent it earlier.
Exercise
Your application moved from READ COMMITTED to SERIALIZABLE in PostgreSQL, and users now sometimes see errors with SQLSTATE 40001. What happened, and what should the application do?
Show answer
At SERIALIZABLE, PostgreSQL detects conflicts between concurrent transactions that could not be ordered one after another, and it aborts one with a serialization failure. The transaction did nothing wrong. The application should catch SQLSTATE 40001, roll back, and run the whole transaction again, usually with a limit on the number of attempts.