Sub topic 3
Dirty reads
This chapter assumes you can write SELECT, INSERT, UPDATE and DELETE statements and use BEGIN, COMMIT and ROLLBACK. It also assumes you know that many clients can use one database at the same time. It uses the vocabulary from the previous chapter: a transaction is a group of statements that succeeds or fails as a unit, and isolation describes how much concurrent transactions can see of each other.
What a dirty read is
A dirty read happens when a transaction reads data that another transaction has changed but not yet committed. The data is "dirty" because it is provisional. The writer can still roll back, and then the value the reader saw never officially existed.
Three facts define the problem:
- The writer has modified a row and has not issued
COMMIT. - The reader sees that modified value instead of the last committed one.
- The writer's outcome is still open. If it rolls back, the reader holds a value that was never part of any committed state of the database.
This breaks the "all or nothing" promise of atomicity from the reader's point of view. A rolled-back transaction should leave no trace. A dirty read lets its half-finished work leak into other transactions before it is undone.
A worked schedule
Take an accounts table with one row: account 1 holds a balance of 100. Session A starts a transfer and temporarily reduces the balance. Session B reads the balance while A is still working. Then A fails and rolls back.
Session B first saw 50. If it made a decision based on that number, such as approving a loan or sending a "low balance" email, the decision rests on a value that was never true. Session B's second read returns 100, so B also sees the data change without any commit. That inconsistency is a bonus problem. The main damage is the first read.
Reproducing it in MySQL
MySQL InnoDB really does allow dirty reads at READ UNCOMMITTED, so it is the easiest engine for a demonstration. Open two client connections.
-- Setup (run once)
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
-- Session A
START TRANSACTION;
UPDATE accounts SET balance = 50 WHERE id = 1;
-- do not commit yet
-- Session B
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
START TRANSACTION;
SELECT balance FROM accounts WHERE id = 1; -- returns 50: a dirty read
-- Session A
ROLLBACK;
-- Session B
SELECT balance FROM accounts WHERE id = 1; -- returns 100
COMMIT;Repeat the experiment with SET TRANSACTION ISOLATION LEVEL READ COMMITTED; in Session B. The first SELECT then returns 100. Session A's uncommitted change is invisible, and B does not wait for A.
What each level says about dirty reads
The SQL standard defines isolation levels by which anomalies they permit. For dirty reads the rule is short.
| Isolation level | Dirty read allowed by the standard? |
|---|---|
| READ UNCOMMITTED | Yes |
| READ COMMITTED | No |
| REPEATABLE READ | No |
| SERIALIZABLE | No |
Any level above READ UNCOMMITTED forbids dirty reads. The later chapters on non-repeatable reads and phantoms explain what the higher levels add on top of this.
The standard describes the minimum a level must prevent, not how an engine behaves. A real engine may be stricter than the standard says, and several are.
How engines treat READ UNCOMMITTED
| Engine | Behavior at READ UNCOMMITTED |
|---|---|
| PostgreSQL | Accepted as a name, but it behaves exactly like READ COMMITTED. Dirty reads never happen. |
| MySQL (InnoDB) | Real dirty reads for ordinary non-locking `SELECT` statements. |
| SQL Server | Real dirty reads. The table hint `WITH (NOLOCK)` gives the same effect for one table in one query. |
| Oracle | Not supported. Requesting it raises an error. The lowest level is READ COMMITTED. |
PostgreSQL accepts the syntax so that code written for other databases still runs, and it quietly gives you the stronger guarantee. You can check this yourself. Run the schedule above in PostgreSQL with Session B declared as BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;, and B reads 100 the whole time. Its architecture, described in the chapter on locks and MVCC, never exposes uncommitted row versions to other transactions.
-- PostgreSQL: the level name is accepted, the behavior is READ COMMITTED
BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SHOW transaction_isolation; -- reports: read uncommitted
SELECT balance FROM accounts WHERE id = 1; -- still returns only committed data
COMMIT;SHOW transaction_isolation reports the name you asked for, so it does not prove which behavior you get. Only a two-session test does.
SQL Server and the NOLOCK hint
SQL Server uses locks by default for READ COMMITTED: a reader waits when a writer holds an exclusive lock on the row. Some teams add WITH (NOLOCK) to queries to avoid that waiting. This is the most common way dirty reads reach production code.
-- SQL Server: two equivalent ways to allow dirty reads
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT balance FROM accounts WHERE id = 1;
SELECT balance FROM accounts WITH (NOLOCK) WHERE id = 1;The cost goes beyond seeing a value that is later rolled back. A scan with NOLOCK over a table that is being modified can skip rows or return the same row twice. This happens, for example, when a page split moves rows while the scan is running. Results may not match any state the table was ever in.
Dirty reads versus dirty writes
A dirty write is different: a transaction overwrites a value that another transaction has written but not yet committed. The standard treats dirty writes as unacceptable at every level, and real engines prevent them by making the second writer wait. The second writer waits for the first to commit or roll back.
You can see this in the MySQL example. While Session A holds its uncommitted UPDATE, a second session running UPDATE accounts SET balance = 70 WHERE id = 1; does not proceed. It blocks on A's row lock until A finishes. Even at READ UNCOMMITTED, dirty reads apply only to reading, not to writing.
Why anyone allows dirty reads
READ UNCOMMITTED exists because it is the cheapest level. Readers neither take locks nor wait for writers. That used to matter in lock-based engines, where readers and writers blocked each other. It remains an option in the following narrow cases:
- Rough monitoring queries, such as an approximate row count or a progress indicator, where an error of a few rows is acceptable.
- Debugging, where you want to inspect what an in-flight transaction has changed.
- Data that is append-only, where uncommitted rows are the only risk and approximate results are fine.
For nearly everything else, the saving is small. MVCC engines let readers see a committed snapshot without blocking anyone, so correct reads cost almost the same as dirty ones. This is why PostgreSQL can safely refuse to implement dirty reads.
Common mistakes
- Assuming the level name tells you the behavior.
READ UNCOMMITTEDmeans dirty reads in MySQL and SQL Server but not in PostgreSQL. Code that works by accident in one engine can break when moved. - Treating a dirty read as harmless because the writer "usually commits". The risk is the rollback path. Rollbacks happen on constraint violations, deadlocks, application errors and dropped connections, and those are the cases you test least.
- Adding
NOLOCKto fix blocking. It removes the symptom (waiting) and hides a design question: why do readers and writers contend for the same rows? - Confusing a dirty read with a non-repeatable read. In a dirty read the value read was never committed. In a non-repeatable read, the value was committed, but a later commit changed it between two of your reads. The next chapter covers that second case.
- Setting the level after the transaction has started. In MySQL the statement raises an error. In PostgreSQL
SET TRANSACTION ISOLATION LEVELmust run before the first query of the transaction, or it fails.
Checking your own system
To find out what your database does, run the two-session test from this chapter against a scratch table. Do not rely on documentation alone, because settings can differ by version and configuration. In MySQL you can also look at the current level:
SELECT @@transaction_isolation; -- MySQL 8.0 and laterAlso search your application code for READ UNCOMMITTED, NOLOCK, and any driver option that sets the isolation level on connect. Connection pool defaults and ORM settings sometimes change the level without anyone noticing.
Exercise
In MySQL, Session A runs START TRANSACTION; UPDATE accounts SET balance = 50 WHERE id = 1; and leaves the transaction open. Session B sets READ UNCOMMITTED, starts a transaction and runs SELECT balance FROM accounts WHERE id = 1;. Then Session A rolls back. (a) What does B's first SELECT return, if the original balance was 100? (b) What does it return if B used READ COMMITTED instead? (c) Why is the answer to (a) a problem?
Show answer
(a) 50, a dirty read of an uncommitted value. (b) 100, because READ COMMITTED shows only committed data and does not wait for A's lock on a plain SELECT in an MVCC engine like InnoDB. (c) The value 50 never became part of the committed database, because A rolled back. B may have acted on a balance that never officially existed.
Exercise
You run the same two-session test on PostgreSQL with Session B declared as READ UNCOMMITTED. What does B read, and why? Name the isolation level whose behavior B actually gets.
Show answer
B reads 100, the last committed value. PostgreSQL accepts the READ UNCOMMITTED syntax but treats it as READ COMMITTED, so uncommitted row versions are never visible to other transactions. B gets READ COMMITTED behavior.
Exercise
A teammate wants to add WITH (NOLOCK) to a SQL Server report query because it sometimes waits on writers. Give two risks of this change and one alternative.
Show answer
Risks: the query can return uncommitted values that are later rolled back, and a scan can skip rows or return rows twice while the table is being modified. Alternative: turn on READCOMMITTEDSNAPSHOT so readers see the last committed version without blocking writers and without dirty reads.