Triggers — Complete Guide
Triggers — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 43 of 100
Triggers
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
Triggers fire automatically on INSERT, UPDATE, DELETE, or TRUNCATE — BEFORE or AFTER the row change. They wire audit logs, derived columns, or validation without app code duplication.
Why should you care?
PostgresVerse must log every balance change even if a buggy service skips application audit — trigger guarantees it.
See it live — copy this example
Run in pgAdmin or psql.
CREATE TABLE balance_audit (
audit_id bigserial PRIMARY KEY,
account_id bigint,
old_balance numeric(14,2),
new_balance numeric(14,2),
changed_at timestamptz DEFAULT now()
);
CREATE TRIGGER trg_accounts_audit
AFTER UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION log_balance_change();
What happened?
- AFTER UPDATE OF balance fires only when balance column changes.
- FOR EACH ROW passes OLD and NEW to trigger function.
- Audit table gets append-only history.
Practice next
- Create balance_audit and stub log_balance_change function (next lesson).
- CREATE TRIGGER as shown.
- UPDATE accounts balance and SELECT audit rows.
- Add WHEN (OLD.balance IS DISTINCT FROM NEW.balance) clause.
- Create INSTEAD OF trigger on a view.
Remember
Triggers enforce cross-cutting rules at database. BEFORE triggers can veto change; AFTER cannot. Keep trigger bodies thin; delegate to functions.
PostgresVerse compliance trail
Regulator asks who changed account 8842 balance; audit trigger answers.
Outcome: App bypass attempt still leaves database-level trail.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!