SQL · Module 13 · Lesson 41 min read

Triggers

What is a trigger?

A function that runs automatically when rows are inserted, updated or deleted (or a table is truncated).

Two parts

  1. A trigger function – RETURNS trigger, written in PL/pgSQL
  2. The trigger – attaches it to a table and event:
SQL
CREATE TRIGGER name
BEFORE | AFTER  INSERT OR UPDATE [OF col] OR DELETE
ON table
FOR EACH ROW | FOR EACH STATEMENT
[WHEN (condition)]
EXECUTE FUNCTION fn();

Special variables inside the function

  • NEW – the new row (INSERT/UPDATE)
  • OLD – the old row (UPDATE/DELETE)
  • TG_OP – 'INSERT', 'UPDATE' or 'DELETE'
  • TG_TABLE_NAME, TG_WHEN

BEFORE vs AFTER

  • BEFORE – can modify NEW before it's saved (set updated_at, normalize text, fill defaults) or cancel the row by returning NULL. Must RETURN NEW (or OLD for DELETE).
  • AFTER – the row is already saved; use it for side effects on other tables (update a balance, write an audit log, send a notification). Return value is ignored (RETURN NULL).

Common uses

  • updated_at = now() on every update ⭐
  • Audit logs: store old/new data as JSONB
  • Denormalized counters & balances
  • Validation too complex for a CHECK constraint
  • Supabase: create a profiles row when a new auth.users row appears
  • pg_notify for realtime events

Cautions

  • Triggers are invisible — document them; surprise side effects confuse developers
  • They run per row → can slow down bulk operations
  • Avoid long chains of triggers firing other triggers
  • Keep business logic that the app owns in the app; use triggers for data integrity and bookkeeping
  • Disable temporarily (bulk loads): ALTER TABLE t DISABLE TRIGGER name;

Example

SQL
-- 1. updated_at maintained automatically (BEFORE UPDATE)
ALTER TABLE expenses ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now();

CREATE FUNCTION set_updated_at() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.updated_at := now();
  RETURN NEW;
END $$;

CREATE TRIGGER expenses_updated_at
BEFORE UPDATE ON expenses
FOR EACH ROW EXECUTE FUNCTION set_updated_at();

-- 2. Clean the data before saving (BEFORE INSERT OR UPDATE)
CREATE FUNCTION normalize_expense() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.title := initcap(trim(regexp_replace(NEW.title, '\s+', ' ', 'g')));
  NEW.tags  := ARRAY(SELECT DISTINCT lower(t) FROM unnest(NEW.tags) t ORDER BY 1);
  RETURN NEW;
END $$;
CREATE TRIGGER expenses_normalize
BEFORE INSERT OR UPDATE OF title, tags ON expenses
FOR EACH ROW EXECUTE FUNCTION normalize_expense();

INSERT INTO expenses (user_id, title, amount, tags)
VALUES (2, '   evening    SNACKS ', 250, '{Social,social,FOOD}')
RETURNING title, tags;                         -- Evening Snacks | {food,social}

-- 3. Audit log (AFTER, stores old and new versions as JSONB)
CREATE TABLE audit_log (
  id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  table_name TEXT, action TEXT, row_id BIGINT,
  old_data   JSONB, new_data JSONB,
  changed_at TIMESTAMPTZ DEFAULT now()
);

CREATE FUNCTION audit_changes() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO audit_log (table_name, action, row_id, old_data, new_data)
  VALUES (TG_TABLE_NAME, TG_OP,
          COALESCE(NEW.id, OLD.id),
          CASE WHEN TG_OP <> 'INSERT' THEN to_jsonb(OLD) END,
          CASE WHEN TG_OP <> 'DELETE' THEN to_jsonb(NEW) END);
  RETURN NULL;
END $$;

CREATE TRIGGER expenses_audit
AFTER INSERT OR UPDATE OR DELETE ON expenses
FOR EACH ROW EXECUTE FUNCTION audit_changes();

UPDATE expenses SET amount = 3500 WHERE id = 12;   -- Fuel: 3000 → 3500
DELETE FROM expenses WHERE id = 3;                 -- Taxi to office

SELECT action, row_id,
       old_data->>'amount' AS old_amount,
       new_data->>'amount' AS new_amount,
       (new_data->>'updated_at') IS NOT NULL AS stamped
FROM audit_log ORDER BY id;
-- UPDATE | 12 | 3000.00 | 3500.00 | t
-- DELETE |  3 | 450.00  | NULL    | f

-- List triggers on a table
SELECT tgname FROM pg_trigger WHERE tgrelid = 'expenses'::regclass AND NOT tgisinternal;