BEFORE & AFTER Triggers

Timing and Row Values

TimingRunsGood for
BEFOREbefore the row is writtenvalidating or changing the incoming values
AFTERafter the row is writtenaudit logs, updating other tables
INSTEAD OFreplaces the actionmaking 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

ProductIDProductNamePrice
2Green Tea 100 bags7.25
UPDATE Products SET Price = -1 WHERE ProductID = 2;
-- Error: Price cannot be negative

AFTER: 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

ProductIDProductNameStock
5Espresso Beans 1kg40