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?

  1. A2
  2. B5
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Database Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Database Basics questions

  1. Among the problems that occur when transactions run concurrently, which correctly describes a dirty read?
  2. Transaction T1 ran SELECT COUNT(*) FROM orders WHERE amount >= 1000 and got 8. Immediately afterwards, T2 inserted an order row with an amount of 2000 and committed. When T1 ran the same SELECT statement again, it got 9. What is this phenomenon?
  3. Among the isolation levels defined by the SQL standard, which correctly lists the phenomena that can occur under READ COMMITTED?
  4. Transaction T1 holds a shared lock on a row and is reading it. T2 requests a shared lock and T3 requests an exclusive lock on the same row. Which is correct for the period until T1 releases its lock?
  5. Which correctly describes two-phase locking (2PL), used for concurrency control of transactions?