Answer: Triggers
Explore how to create and implement MySQL triggers that automatically update values like restock dates when product stock changes. Understand trigger syntax, timing, and event handling, with examples and alternative approaches for enforcing business logic within the database.
We'll cover the following...
Solution
The solution is given below:
Explanation
The explanation of the solution code is given below:
Line 2: The
DELIMITER //command sets a temporary delimiter so that semicolons inside the trigger body do not terminate theCREATE TRIGGERstatement too early. This is required when defining multiple-statement routines or triggers in MySQL.Lines 4–12: A row-level trigger
trg_update_restock_dateis created on theProductstable to run before each update.CREATE TRIGGER trg_update_restock_datedefines the trigger name.BEFORE UPDATE ON Productsspecifies that it fires before any update to rows inProducts, so the trigger can adjust column values before they are stored.FOR EACH ROWensures the logic runs separately for every row that is updated by the statement.BEGINandEND //wrap the trigger body as a single execution block using the custom delimiter.Inside the block,
IF NEW.Stock > OLD.Stock THENchecks whether the newStockvalue is greater than the old one, meaning the product has been restocked.When that condition is true,
SET NEW.LastRestockDate = CURDATE();updates theLastRestockDatecolumn in the new row to today’s date before the row is written.
Line 14: ...