Careeroza
BEFORE & AFTER Triggers
Timing and Row Values
| Timing | Runs | Good for |
|---|---|---|
BEFORE | before the row is written | validating or changing the incoming values |
AFTER | after the row is written | audit logs, updating other tables |
INSTEAD OF | replaces the action | making views writable |
Inside a row trigger, NEW is the row after the change (INSERT, UPDATE) and OLD is the row before it (UPDATE, DELETE). SQL Server uses the pseudo-tables inserted and deleted instead.
BEFORE: Validate
Example
Reject negative prices with a clear error message:
CREATE TRIGGER trg_products_price_check
BEFORE UPDATE OF Price ON Products
FOR EACH ROW
WHEN NEW.Price < 0
BEGIN
SELECT RAISE(ABORT, 'Price cannot be negative');
END;
UPDATE Products SET Price = 7.25 WHERE ProductID = 2;
SELECT ProductID, ProductName, Price FROM Products WHERE ProductID = 2;Result: 1 row
| ProductID | ProductName | Price |
|---|---|---|
| 2 | Green Tea 100 bags | 7.25 |
UPDATE Products SET Price = -1 WHERE ProductID = 2;
-- Error: Price cannot be negativeAFTER: Keep Stock in Sync
Example
Reduce stock automatically when an order line is inserted:
CREATE TRIGGER trg_orderdetails_stock
AFTER INSERT ON OrderDetails
FOR EACH ROW
BEGIN
UPDATE Products SET Stock = Stock - NEW.Quantity WHERE ProductID = NEW.ProductID;
END;
INSERT INTO OrderDetails (OrderDetailID, OrderID, ProductID, Quantity) VALUES (13, 108, 5, 5);
SELECT ProductID, ProductName, Stock FROM Products WHERE ProductID = 5;Result: 1 row
| ProductID | ProductName | Stock |
|---|---|---|
| 5 | Espresso Beans 1kg | 40 |