Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 151/ 160
08. Transactions, Security & Production SQL Administration

Triggers (BEFORE / AFTER, FOR EACH ROW / STATEMENT) & Audit Logging

Automate audit trails and invariants with BEFORE/AFTER row and statement triggers.

AdvancedBEFORE / AFTER · Row vs Statement3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

An audit trigger (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE FUNCTION log_salary()2RETURNS trigger3LANGUAGE plpgsql4AS $$5BEGIN6IF NEW.salary IS DISTINCT7FROM OLD.salary THEN8INSERT INTO salary_audit (emp_id,9  old_salary,10  new_salary,11  changed_by,12  changed_at)13VALUES (OLD.id,14  OLD.salary,15  NEW.salary,16  current_user,17  now());18END IF;19RETURN NEW;20END $$;2122CREATE TRIGGER salary_audit AFTER23UPDATE ON employees FOR EACH ROW EXECUTE FUNCTION log_salary();
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/23
3OutputInspect the representative rows, affected-row count, plan, or command status.
Audit objects created
CREATE FUNCTION CREATE TRIGGER

Note: PostgreSQL-style command tags. A salary_audit row is produced only when a later employee salary update changes the value.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Keeping updated_at correctQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TRIGGER set_updated_at2BEFORE UPDATE ON orders FOR EACH ROW3EXECUTE FUNCTION touch_updated_at ();
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Trigger creation status
CREATE TRIGGER

Note: The timestamp update occurs on subsequent UPDATEs and assumes touch_updated_at() already exists with the described behavior.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

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.

Focus at this step

audit for all writers → trigger

What to watch at this step
Prefer first
constraints
Tip: use ← → to move between steps

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

Database trigger
Best for: Rules and audit trails that must cover every writer

Strengths: Can't be bypassed; same transaction as the change.

Watch out: Hidden behaviour, slower writes, harder debugging.

Application code
Best for: Audit and side effects owned by one service

Strengths: Visible, testable, can include request context (user, IP).

Watch out: Scripts and other services can bypass it.

Change data capture (CDC)
Best for: Streaming changes to other systems at scale

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?
Interview tip: Show one audit trigger, then list its costs (hidden, slower writes, bypassed by TRUNCATE) and mention CDC as an alternative. It shows you'd use triggers deliberately, not by default.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Stored Procedures & Transaction Control Inside Procedures
Next topic
Users, Roles & Privilege Management (GRANT, REVOKE)