Database Triggers

Difficulty: Intermediate

Question

What are database triggers, what are good use cases for them, and what are the risks of relying on them?

Answer

A trigger is a function that the database runs automatically when a specific event happens on a table, such as an INSERT, UPDATE or DELETE. Triggers fire inside the same transaction as the statement that caused them, so they can validate, modify or record changes in a way that no application code path can skip. They are great for audit logs, timestamps and denormalized counters, but hidden logic and extra write cost make them risky for general business rules.

How triggers are defined

A trigger has a few parts:

  • Event: INSERT, UPDATE (optionally UPDATE OF column), DELETE, and in PostgreSQL also TRUNCATE.
  • Timing: BEFORE runs before the row is written and can change or reject it; AFTER runs after and is used for side effects; INSTEAD OF replaces the operation, used on views.
  • Granularity: FOR EACH ROW fires once per affected row with access to OLD and NEW; FOR EACH STATEMENT fires once per statement.
  • Condition: an optional WHEN (...) clause skips the trigger when it is not needed.

Vendor notes: PostgreSQL triggers call a trigger function (EXECUTE FUNCTION, which replaced EXECUTE PROCEDURE syntax in v11) and support statement-level triggers with transition tables (REFERENCING NEW TABLE AS). MySQL supports only row-level triggers, with BEFORE and AFTER timing.

Good use cases

  • Audit trails: copy OLD and NEW values into an audit_log table on every change to sensitive tables like accounts or kyc_details. Even a manual SQL fix by an engineer gets logged.
  • Automatic timestamps: set updated_at = now() in a BEFORE UPDATE trigger. MySQL can do this without a trigger using ON UPDATE CURRENT_TIMESTAMP; PostgreSQL needs a trigger.
  • Maintaining denormalized data: keep posts.comment_count or a search tsvector column in sync.
  • Complex integrity rules that a CHECK or foreign key cannot express, like "a doctor cannot have overlapping appointments" (though an exclusion constraint may be better in PostgreSQL).
  • Outbox or notification hooks: write to an outbox table or call pg_notify so other services learn about changes.

Risks and downsides

  • Hidden behaviour. A developer reading the app code sees one INSERT and has no idea it also writes three other tables. Debugging gets hard.
  • Write performance. A row-level trigger on a bulk update of a million rows runs a million times, inside the same transaction, holding locks longer.
  • Cascading triggers. One trigger updates a table that has its own trigger, and so on. This can cause unexpected loops or deadlocks.
  • Bulk loads and migrations. Triggers fire during data backfills too, unless deliberately disabled.
  • Portability and testing. Trigger code is vendor-specific and usually poorly tested.
  • Not for external calls. Never call HTTP APIs or send emails from a trigger; if the transaction rolls back, the email has already gone. Use an outbox table instead.

Rule of thumb

Use triggers forKeep in application code
Audit loggingBusiness workflows and pricing rules
updated_at timestampsAnything calling external services
Simple denormalized countersLogic that changes often
Last-line integrity checksLogic the team needs to test easily
What happens when a row is updated. Triggers run inside the same transaction as the original statement.
  1. UPDATE statement starts: Application changes an account row.
  2. BEFORE trigger fires: Can modify NEW values or reject the change.
  3. Row is written: Table and indexes are updated.
  4. AFTER trigger fires: Writes OLD and NEW values to the audit log.
  5. Transaction commits: All changes, including trigger writes, commit together.

Code examples

Audit trigger in PostgreSQL

CREATE TABLE audit_log (
  id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  table_name TEXT NOT NULL,
  op         TEXT NOT NULL,
  old_row    JSONB,
  new_row    JSONB,
  changed_by TEXT NOT NULL DEFAULT current_user,
  changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE OR REPLACE FUNCTION log_change() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
  INSERT INTO audit_log (table_name, op, old_row, new_row)
  VALUES (TG_TABLE_NAME, TG_OP,
          CASE WHEN TG_OP <> 'INSERT' THEN to_jsonb(OLD) END,
          CASE WHEN TG_OP <> 'DELETE' THEN to_jsonb(NEW) END);
  RETURN NULL;  -- return value is ignored for AFTER triggers
END;
$;

CREATE TRIGGER accounts_audit
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW EXECUTE FUNCTION log_change();

Every change to accounts, from the app or a manual psql session, is recorded with before and after values in the same transaction.

Keeping updated_at current

CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
  NEW.updated_at := now();
  RETURN NEW;   -- BEFORE triggers must return the row to write
END;
$;

CREATE TRIGGER orders_set_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION set_updated_at();

A BEFORE trigger edits NEW before it is stored. Returning NULL from a BEFORE row trigger would silently skip the update.

Key points

  • Triggers run automatically on INSERT, UPDATE, DELETE (and TRUNCATE in PostgreSQL)
  • BEFORE triggers can modify or reject rows; AFTER triggers handle side effects
  • Triggers run in the same transaction, so they cannot be bypassed and roll back together
  • MySQL supports only row-level triggers; PostgreSQL also supports statement-level
  • Avoid triggers for external calls and frequently changing business logic

Common follow-up questions

  • What is the difference between a row-level and a statement-level trigger?
  • How would you implement an audit log without triggers, for example with CDC?
  • Why should you not send emails from a trigger? What is the outbox pattern?
  • How do triggers interact with bulk inserts and replication?

Interview tips

  • Give one strong use case (audit logging) and one clear anti-pattern (calling external APIs)
  • Mention that triggers run in the same transaction; it explains both their power and their cost
  • Show balance: say you would keep business workflows in the app and use triggers sparingly

Concepts covered

Database Triggers, BEFORE and AFTER Triggers, Row-level vs Statement-level, Audit Logging, Transition Tables

More Database Design questions