Sub topic 6
Choosing events, UPDATE OF columns, and WHEN conditions
This chapter assumes you can write a trigger function and attach it with CREATE TRIGGER, and that you know the difference between row-level and statement-level triggers. It covers three filters that decide whether a trigger function runs at all: the event list, the UPDATE OF column list, and the WHEN condition. Using them well keeps triggers cheap and predictable.
Three filters, applied in order
PostgreSQL checks the filters in this order for each affected row:
- The command must match one of the events listed in the trigger.
- For
UPDATE OF, one of the listed columns must be a target of the command. - If there is a
WHENcondition, it must evaluate to true.
Only then does the trigger function run.
Choosing events
A trigger listens for one or more of INSERT, UPDATE, DELETE, and TRUNCATE. Join several events with OR:
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
balance numeric(12,2) NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION forbid_negative_balance() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.balance < 0 THEN
RAISE EXCEPTION 'balance cannot be negative: %', NEW.balance
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_check_balance
BEFORE INSERT OR UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION forbid_negative_balance();Keep these rules in mind:
TRUNCATEtriggers must beFOR EACH STATEMENT. A truncate does not visit rows, so it never firesDELETEtriggers.COPY ... FROMfiresINSERTtriggers, as ordinary inserts do.INSERT ... ON CONFLICT DO UPDATEfiresBEFORE INSERTrow triggers first. TheUPDATEtriggers fire only for rows that took the update path.- Inside the function,
TG_OPtells you which event fired when a trigger lists several.OLDdoes not exist for inserts, andNEWdoes not exist for deletes.
UPDATE OF: filter by the SET list
UPDATE OF col1, col2 fires the trigger only when at least one listed column appears as a target in the SET clause. The check looks at the command, not the data. Setting a column to the value it already has still counts.
CREATE FUNCTION notice_fire() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'fired: % (% on %)', TG_NAME, TG_OP, TG_TABLE_NAME;
RETURN NULL;
END;
$$;
CREATE TRIGGER t_balance
AFTER UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION notice_fire();Two details catch people out:
- The column list applies only to
UPDATE. InINSERT OR UPDATE OF balance, the insert part always fires. - If a
BEFORE UPDATEtrigger assigns to a listed column inside the function, that does not make anUPDATE OFtrigger fire. Only the originalSETlist counts.
WHEN: filter by the data
A WHEN condition is a boolean expression, in parentheses, evaluated per row. It can read OLD and NEW. Because it compares actual values, it catches what UPDATE OF cannot:
CREATE TRIGGER t_changed
AFTER UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
EXECUTE FUNCTION notice_fire();Try these statements and compare which trigger fires:
INSERT INTO accounts (email, balance) VALUES ('[email protected]', 100);
UPDATE accounts SET balance = 100 WHERE email = '[email protected]';
UPDATE accounts SET email = '[email protected]' WHERE email = '[email protected]';
UPDATE accounts SET balance = 150 WHERE email = '[email protected]';| Statement | `t_balance` (UPDATE OF balance) | `t_changed` (WHEN balance differs) |
|---|---|---|
| `SET balance = 100` (same value) | fires | skipped |
| `SET email = ...` | skipped | skipped |
| `SET balance = 150` | fires | fires |
Use IS DISTINCT FROM rather than <>. A comparison involving NULL yields NULL, and a WHEN that yields NULL counts as false. A change from NULL to a value, or the reverse, would be missed with <>.
Skipping no-op updates
A common pattern is to compare the whole row. The updated_at trigger from the earlier example becomes:
CREATE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION set_updated_at();An update that rewrites identical values leaves updated_at alone. The WHEN test runs before the function, so it sees the row as the UPDATE produced it. The comparison needs every column type to have an equality operator. A table with a json column raises an error here. Use jsonb, or compare specific columns instead.
Limits of WHEN
INSERTtriggers cannot referenceOLD, andDELETEtriggers cannot referenceNEW. PostgreSQL rejects these when you create the trigger.- Statement-level triggers cannot reference
OLDorNEWinWHEN, because no single row exists. INSTEAD OFtriggers do not acceptWHEN.BEFOREtriggers cannot read system columns such asctidinWHEN.- Subqueries are not allowed. Move that logic into the function.
Why filter outside the function
For a BEFORE trigger, a WHEN test is equivalent to an IF at the top of the function. The advantage is clarity, because the firing rule shows up in the trigger definition and in \d accounts. For an AFTER row trigger, the advantage is larger. PostgreSQL queues AFTER events until the statement ends, and a WHEN that is false means the event is never queued. On a bulk update that changes few rows, this saves both calls and memory.
Pick the filter by what you need to detect:
- Use
UPDATE OFwhen the question is "did the command touch this column?" It is cheap and needs no expression. - Use
WHENwhen the question is "did the value actually change?" or depends on row values. - Combine them when both apply.
UPDATE OF balanceplusWHEN (NEW.balance < 0)limits the trigger to commands that set the column, and then to bad values. - Use separate triggers when different events need different conditions. One
WHENcovers the whole trigger, soINSERT OR UPDATEwith aWHENthat readsOLDfails.
Exercise
You want a trigger that logs only when accounts.email actually changes to a different value, ignoring updates that set it to the same value or that touch other columns. Which clauses do you write, and why is UPDATE OF email alone not enough?
Show answer
Use AFTER UPDATE OF email ON accounts FOR EACH ROW WHEN (OLD.email IS DISTINCT FROM NEW.email). UPDATE OF email only checks that email appears in the SET list, so UPDATE accounts SET email = email would still fire the trigger. The WHEN condition compares the old and new values and skips that case. IS DISTINCT FROM also handles NULL correctly.