Triggers (BEFORE / AFTER, FOR EACH ROW / STATEMENT) & Audit Logging
Automate audit trails and invariants with BEFORE/AFTER row and statement triggers.
In plain words
A trigger is a rule like "whenever someone changes this table, also do that", and the database does it automatically.
Think of it like…
A motion-sensor camera at a warehouse door: whoever comes in and whatever they carry, it records automatically. Nobody has to remember to switch it on, but nobody notices it either until they look at the footage.
Where you’ve seen it
An audit log for salary changes: an AFTER UPDATE trigger on employees writes the old and new salary, who changed it and when into salary_audit, whether the change came from the HR app, an admin script or a data fix.
Words you’ll hear
- BEFORE / AFTER / INSTEAD OF
- When the trigger runs relative to the change; INSTEAD OF is for views.
- FOR EACH ROW / STATEMENT
- Fire once per affected row, or once per statement.
- OLD / NEW
- The row before and after the change, available in row-level triggers.
- Transition tables
- In PostgreSQL 10+, statement triggers can read all changed rows as a table.
Visual diagram
Theory & example queries
BEFORE vs AFTER, row vs statement
A BEFORE ROW trigger receives the proposed NEW row and can change it (set updated_at, lowercase an email) or cancel it by returning NULL in PostgreSQL. It's for normalising and validating data. An AFTER ROW trigger runs once the row is written and sees its final values, which makes it the right place to write audit records or notify other systems.
Row-level triggers fire once per affected row, so an UPDATE of a million rows fires a million times. Statement-level triggers fire once; in PostgreSQL 10+ they can read every changed row through transition tables (REFERENCING NEW TABLE AS …), which is far more efficient for bulk changes.
CREATE FUNCTION log_salary()RETURNS triggerLANGUAGE plpgsqlAS $$BEGINIF NEW.salary IS DISTINCTFROM OLD.salary THENINSERT INTO salary_audit (emp_id, old_salary, new_salary, changed_by, changed_at)VALUES (OLD.id, OLD.salary, NEW.salary, current_user, now());END IF;RETURN NEW;END $$;CREATE TRIGGER salary_audit AFTERUPDATE ON employees FOR EACH ROW EXECUTE FUNCTION log_salary();PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Audit objects created
Note: PostgreSQL-style command tags. A salary_audit row is produced only when a later employee salary update changes the value.
Key takeaway: BEFORE to modify or validate, AFTER to audit; prefer statement triggers for bulk work.
The costs of triggers
Triggers are invisible from the application code, so a developer reading UPDATE employees … has no idea it also writes to another table. They add work to every write, can cascade (a trigger that updates a table with its own triggers) and make bulk loads much slower. They also run inside the same transaction, so a failing trigger rolls back the change that fired it.
Some operations skip them: TRUNCATE doesn't fire DELETE triggers. For audit trails and syncing other systems, alternatives include writing audit rows from the application, or change data capture (PostgreSQL logical decoding with tools such as Debezium), which reads the write-ahead log without slowing writes.
CREATE TRIGGER set_updated_atBEFORE UPDATE ON orders FOR EACH ROWEXECUTE FUNCTION touch_updated_at ();PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Trigger creation status
Note: The timestamp update occurs on subsequent UPDATEs and assumes touch_updated_at() already exists with the described behavior.
where the function sets NEW.updated_at = now() and returns NEW.
Key takeaway: Triggers are reliable but hidden and costly; document them and consider CDC for heavy audit needs.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide if a trigger is the right tool
Use one when every writer must be covered (audit, updated_at, derived columns) and a constraint can't express the rule.
audit for all writers → trigger
When to use it & trade-offs
What it is
A trigger runs a function automatically when rows are inserted, updated or deleted. BEFORE triggers run before the change and can modify or reject the new row; AFTER triggers run once the change is made and are typical for audit logs. FOR EACH ROW fires once per affected row; FOR EACH STATEMENT fires once per statement however many rows it touches.
Why it matters: Triggers enforce rules and record history for every writer, including scripts and other services that bypass the application. They're also a common source of hidden behaviour and slow bulk operations. Interviewers ask when you'd use one, and what the downsides are.
When to reach for it
- Audit logs for sensitive tables
- Maintaining updated_at and similar derived columns
- INSTEAD OF triggers to make complex views writable
When to avoid or be careful
- Business workflows hidden in chains of triggers
- External calls (HTTP, email) inside triggers
- Row-level triggers on tables that receive huge bulk loads
Triggers vs application logic vs change data capture
Strengths: Can't be bypassed; same transaction as the change.
Watch out: Hidden behaviour, slower writes, harder debugging.
Strengths: Visible, testable, can include request context (user, IP).
Watch out: Scripts and other services can bypass it.
Strengths: Reads the WAL without slowing writes; captures everything.
Watch out: Extra infrastructure (Debezium, Kafka) to run.
Interview signals & numbers to know
When this topic comes up
- “Who changed this value and when?”
- “BEFORE vs AFTER triggers”
- Mysterious extra writes
- Slow bulk updates
- Audit requirements
Benchmarks & rules of thumb
- 1 per row
- firings of a FOR EACH ROW trigger
- 1 per statement
- firings of a FOR EACH STATEMENT trigger
- PostgreSQL 10
- transition tables for statement triggers
Common mistakes & follow-ups
Common interview mistakes
- Auditing in a BEFORE trigger, so the log records values that a later BEFORE trigger then changes before the row is saved.
- Forgetting that TRUNCATE bypasses DELETE triggers, leaving gaps in the audit log.
- Writing a trigger that updates its own table, causing recursion.
Likely interviewer follow-ups
- When would you use a BEFORE trigger instead of an AFTER trigger?
- What are the downsides of using triggers for business logic?
- How would you audit changes to a table without slowing down writes?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Triggers (BEFORE / AFTER, FOR EACH ROW / STATEMENT) & Audit Logging with hands-on SQL practice and interview Q&A.