1 Detailed Study of Triggers
TopBuilding on the trigger basics from the Intermediate course, let's examine how triggers work internally and explore advanced patterns.
Trigger Execution Order
When you run an INSERT, here's the exact sequence:
- BEFORE INSERT trigger fires — you can modify
NEWvalues - Row is inserted into the table
- Constraints checked (PRIMARY KEY, FOREIGN KEY, CHECK, UNIQUE)
- Indexes updated
- AFTER INSERT trigger fires — you can read
NEWbut not modify it
Key insight: BEFORE triggers can change the data being written (SET NEW.col = value). AFTER triggers cannot — the row is already committed. Use BEFORE for validation/normalization, AFTER for logging/syncing.
Multi-Statement Trigger
DELIMITER //
CREATE TRIGGER trg_order_complete
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
-- 1. Update inventory
UPDATE products
SET stock = stock - NEW.quantity
WHERE id = NEW.product_id;
-- 2. Log the sale
INSERT INTO sales_log (order_id, product_id, qty, logged_at)
VALUES (NEW.id, NEW.product_id, NEW.quantity, NOW());
-- 3. Update customer stats
UPDATE customers
SET total_orders = total_orders + 1,
last_order_date = NOW()
WHERE id = NEW.customer_id;
END //
DELIMITER ;Trigger chains: If a trigger on table A updates table B, and table B has its own trigger, that trigger fires too. This can create cascading chains that are difficult to debug. Keep triggers simple and document them thoroughly.
Key Takeaways
- BEFORE triggers can modify
NEWvalues; AFTER triggers cannot - Triggers execute in order: BEFORE → row write → constraints → indexes → AFTER
- Multi-statement triggers can update inventory, log events, and sync tables automatically
- Be cautious of trigger chains — they create invisible side effects