Database triggers are special automated procedures in a database that are automatically executed when certain events occur on a table or view.
Imagine you have a table called Orders, and you want to automatically log every time an order is deleted.
You can create a DELETE trigger on the Orders table that inserts a message into a Log table whenever a row is deleted.
| Type | Description |
|---|---|
| BEFORE | Executes before the triggering action |
| AFTER | Executes after the triggering action |
| INSTEAD OF | (for views) replaces the triggering action |
CREATE TRIGGER log_delete
AFTER DELETE ON Orders
FOR EACH ROW
BEGIN
INSERT INTO Log (action, timestamp)
VALUES ('Order deleted', NOW());
END;
Data validation
Audit logging
Enforcing business rules
Extending referential integrity
Can be hard to debug
Might trigger other actions unexpectedly
Can impact performance if overly complex