Database Basics
The stock count of a product in a stock table is 10. Transaction T1 reads the stock count and writes back the value minus 3, and T2 reads the stock count and writes back the value minus 5. If they run without locks in the order T1 reads, T2 reads, T1 writes, T2 writes, what is the final stock count?
- A2
- B5
- C7
Show answer and explanation
Answer: B. 5
T1 and T2 both read the stock count of 10 before the other has written. T1 writes 10 − 3 = 7, but T2 then overwrites it with 10 − 5 = 5, calculated from the 10 it read, so the final stock count is 5. It should have been 10 − 3 − 5 = 2, the result of performing the two operations one after the other; T1's update has been lost. This is called a lost update. To prevent it, either take an exclusive lock when reading so that T2's read waits until T1 finishes (for example with SELECT … FOR UPDATE), or perform the read and write in a single SQL statement, as in UPDATE stock SET qty = qty - 3.
- A. This is the correct value when the two operations run one after the other, but in this order T1's update is lost.
- B. Correct. T2 overwrites with 5, calculated from the old value 10, and T1's update is lost.
- C. This is the value T1 wrote. T2 overwrites it afterwards.