Databases

Transactions and Isolation Levels

When transactions access the same data concurrently, one may see another's intermediate changes. Isolation levels define which changes are visible. Stronger isolation restricts anomalies but can impose waiting or other concurrency costs.

A simulator showing how transaction order and isolation affect read results

1. Choose a scenario and isolation level

Scenario
Isolation level

2. Execute in time order

Database

T1 is on the left and T2 on the right. Run the same scenario at different isolation levels to compare what T1 reads. The corresponding matrix cell is highlighted below.

A · AtomicityAll or nothing
C · ConsistencyPreserve constraints
I · IsolationControl interference
D · DurabilityCommitted data persists

Three read anomalies

Dirty Read means reading a value that another transaction has not committed. If that transaction rolls back, the value was never part of the committed state. Non-repeatable Read occurs when a transaction rereads the same row after another transaction has changed and committed it, producing a different value. Phantom Read occurs when repeating a predicate query returns a different set of rows because another transaction has inserted matching rows.

Defaults and implementations vary

PostgreSQL and Oracle default to READ COMMITTED; MySQL InnoDB defaults to REPEATABLE READ. Many databases use MVCC to retain older versions and let reads proceed without waiting for writes. MySQL InnoDB's snapshot reads under REPEATABLE READ prevent the phantom in this example. The SERIALIZABLE simulation here illustrates a lock-based implementation.

Common interview topic

Stronger isolation may reduce concurrent throughput. With locks, more transactions may wait and deadlocks can become more likely. Read-then-update tasks such as reducing inventory often use SELECT ... FOR UPDATE to lock the relevant rows explicitly.