Dirty Read
Definition
Dirty read means one transaction can read data modifications not yet committed by another transaction. Since these data modifications may be rolled back, the read data may be invalid or inconsistent.
Causes
Dirty read typically occurs when database isolation level is set to “Read Uncommitted”.
Specific Manifestation
- Transaction A modifies a record but has not yet committed
- Transaction B reads the record modified by transaction A
- If transaction A ultimately rolls back, then the data read by transaction B is invalid
Solutions
- Raise transaction isolation level to “Read Committed” or higher
- Set appropriate lock mechanism at database level
Non-Repeatable Read
Definition
Non-repeatable read means within the same transaction, due to modifications by other concurrent transactions, the results of reading the same data twice are inconsistent.
Detailed Example
- Transaction A first query: Returns result 1000
- Transaction B executes and commits: UPDATE account SET balance = 800
- Transaction A queries again: Returns result 800
At this point, transaction A finds the two read results are inconsistent.
Solutions
- Raise transaction isolation level to REPEATABLE READ or above
- Use pessimistic lock (SELECT FOR UPDATE)
- Implement optimistic concurrency control at application layer
Repeatable Read
Basic Concept
Repeatable read is the main characteristic of database transaction isolation level REPEATABLE READ, ensuring consistent results when reading the same data multiple times within a transaction.
Core Features
- Prevents non-repeatable read: Through Multi-Version Concurrency Control (MVCC) technology
- Based on snapshots: Based on data snapshot created when transaction starts
Problems Solved
- Dirty read problem
- Non-repeatable read problem
Phantom Read
Definition
Phantom read refers to within the same transaction, due to other concurrent transactions’ insert or delete operations, the same query executed twice returns different result sets.
Specific Manifestation
- Transaction A first query returns N records
- Transaction B inserts new data within that range and commits
- Transaction A executes the same query again, returns N+1 records
Difference from Non-Repeatable Read
- Non-repeatable read: For existing rows whose data is modified
- Phantom read: For new or deleted rows causing result set changes
Solutions
- Raise isolation level to SERIALIZABLE
- Use Gap Lock or Next-Key Lock
- Use pessimistic lock (such as SELECT…FOR UPDATE)
Summary
| Problem | Occurring Isolation Level | Solution |
|---|---|---|
| Dirty Read | READ UNCOMMITTED | Raise isolation level |
| Non-Repeatable Read | READ COMMITTED | Use REPEATABLE READ |
| Phantom Read | REPEATABLE READ | Use SERIALIZABLE |