Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 13 / Topic 7 of 8

Triggers

A trigger runs a function automatically on data changes — the tool for rules that must hold no matter which app writes. The classic: an audit log for price changes.

CREATE TABLE price_audit (
  audit_id   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  product_id integer NOT NULL,
  old_price  numeric(10,2),
  new_price  numeric(10,2),
  changed_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION log_price_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF NEW.price IS DISTINCT FROM OLD.price THEN
    INSERT INTO price_audit (product_id, old_price, new_price)
    VALUES (OLD.product_id, OLD.price, NEW.price);
  END IF;
  RETURN NEW;
END;
$$;
CREATE TRIGGER trg_price_audit
AFTER UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION log_price_change();
UPDATE products SET price = 1150.00 WHERE product_id = 1;
SELECT product_id, old_price, new_price FROM price_audit;
CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
UPDATE 1
 product_id | old_price | new_price 
------------+-----------+-----------
          1 |   1200.00 |   1150.00
(1 row)

The moving parts: a trigger function RETURNS trigger and sees OLD and NEW (the row before and after); the trigger binds it to a table and a moment. AFTER triggers observe and record; BEFORE triggers may modify NEW (normalise an email) or veto the row (RETURN NULL). FOR EACH ROW fires per row; FOR EACH STATEMENT once per statement. Note the Part 3 payoff: IS DISTINCT FROM compares possibly-NULL prices honestly.

Powers this big carry a bill: triggers are invisible in the calling code, they run inside every write's transaction (slow trigger = slow writes everywhere), and trigger-calls-trigger chains turn one UPDATE into an archaeology dig. Audit trails, derived-data upkeep, enforcement no app can bypass — yes. Business workflows — see section 8.

🧪 Quick quiz — answer from memory, then check.

  1. What are OLD and NEW in a row trigger?
  2. What must a trigger function be declared to return?
Show the answers
  1. The row's before- and after-images (UPDATE has both; INSERT only NEW; DELETE only OLD).
  2. The type trigger — and a BEFORE row trigger returns NEW (or NULL to skip the row).

Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.

Search the guide