Middle
What is Dirty Read and what are its features?
sobes.tech AI
Answer from AI
Dirty Read is a problem in working with databases in a multi-user environment, where one transaction reads data that has been modified (but not yet committed) by another transaction. If the transaction that changed the data ultimately rolls back, the data read by the first transaction will be incorrect or "dirty".
Features:
- Non-repeatable Read: Although Dirty Read is related to non-repeatable reads, it is more critical. Non-repeatable read occurs when a transaction reads the same data twice and gets different values due to committed changes by another transaction. Dirty Read reads uncommitted changes.
- Lost Update: Dirty Read can lead to lost updates. If Transaction 1 reads an uncommitted change from Transaction 2 and then writes its change over it, not considering the rollback of Transaction 2, the change from Transaction 2 will be lost.
- Isolation Level: Dirty Read is possible at the lowest isolation level
READ UNCOMMITTED. This level allows reading uncommitted data. - Prevention: Higher isolation levels such as
READ COMMITTEDor above are used to prevent Dirty Reads. At these levels, a transaction can only read committed data.
Example:
| Time | Transaction A | Transaction B |
|---|---|---|
| T1 | Begin Transaction A |
|
| T2 | Begin Transaction B |
|
| T3 | UPDATE balance SET amount = amount - 100 WHERE account_id = 1; (not committed) |
|
| T4 | SELECT amount FROM balance WHERE account_id = 1; (Dirty Read) |
|
| T5 | ROLLBACK; |
|
| T6 | Processing data from T4 (with incorrect value) |
In this example, Transaction A read the changed but uncommitted balance value, which was then rolled back by Transaction B. Transaction A continues working with incorrect data.