Answer: Transactions
Explore how to use transactions in MySQL to group multiple statements into atomic units. Understand techniques like row-level locking with SELECT FOR UPDATE, session variables, and rollback mechanisms. This lesson helps you safely handle concurrent data modifications and maintain consistency during complex operations.
We'll cover the following...
Solution
The solution is given below:
Explanation
The explanation of the solution code is given below:
Lines 2–3: The
SETcommands define two session variables:@product_idto identify the product and@qtyto represent the quantity to be decremented.Line 6: The
START TRANSACTIONstatement begins an explicit transaction, so all subsequent statements execute as a single atomic unit of work.Lines 9–12: The
SELECT ... FOR UPDATEstatement reads the currentStockvalue for the specified product and stores it in@before_stock. It also locks the row so that other concurrent transactions cannot modify it until the current transaction ends.Lines 15–17: The
UPDATEstatement temporarily decrements the stock value by@qty. Because the transaction has not yet been committed, the change ...