SQL ยท Chapter 39 of 42
SQL Triggers
A TRIGGER is code that runs AUTOMATICALLY in response to an event (INSERT/UPDATE/DELETE) on a table.
Use cases: auditing, keeping derived columns in sync, enforcing complex rules.
Example 1 (sql)
-- Log every user delete
CREATE TRIGGER log_deletes
AFTER DELETE ON users
FOR EACH ROW
INSERT INTO audit_log(user_id, action) VALUES (OLD.id, 'delete');Output
Trigger createdRuns after every DELETE on users.
Example 2 (sql)
-- Auto-update updated_at (Postgres)
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION update_timestamp();Output
Trigger createdCommon pattern to keep an updated_at column current.
Key points
- Runs automatically on events.
- BEFORE or AFTER the event.
- FOR EACH ROW or FOR EACH STATEMENT.
- Powerful but easy to over-use โ makes debugging harder.
๐ก Note: Triggers happen behind the scenes. A junior developer may not know why 'INSERT' is also touching 3 other tables. Document them well.
