Junior — Middle
Explain the differences between phantom reads and non-repeatable reads in the context of transactions and data isolation.
sobes.tech AI
Answer from AI
In the context of transactions and data isolation:
-
Non-repeatable Read occurs when, within a single transaction, the same data query returns different results because another transaction has modified and committed those data between the two reads.
-
Phantom Read is a situation where, during a transaction, a repeated query with a condition (e.g., selecting rows based on a criterion) reveals new rows that were not visible during the first read because another transaction inserted or deleted rows matching the condition.
Main difference:
- Non-repeatable read is related to changes in the values of already read rows.
- Phantom read is related to the appearance or disappearance of new rows matching the selection condition.
Example:
- Transaction A reads all customer orders with an amount > 1000.
- Transaction B adds a new order with an amount of 1500 and commits.
- Transaction A repeats the same query and sees the new "phantom" order.
To prevent these phenomena, transaction isolation levels are used, for example, Repeatable Read prevents non-repeatable reads, and Serializable prevents phantom reads.