Sub topic 6
Choosing Events, `UPDATE OF` Columns, and `WHEN` Conditions
Assume you know basic INSERT, UPDATE, DELETE, CREATE TABLE, transactions, and simple PL/pgSQL. This chapter focuses on deciding when a trigger should run, not on writing complex trigger functions.
Choose the database event
A trigger can respond to one or more table events:
INSERTruns when a row is added.UPDATEruns when a row is modified.DELETEruns when a row is removed.TRUNCATEruns when a table is emptied withTRUNCATE.
You can combine events when one function handles them:
CREATE TRIGGER accounts_changes
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();TRUNCATE is different because it removes rows as a set. It supports statement-level triggers, but it does not provide OLD or NEW row values.
Limit updates with `UPDATE OF`
An update trigger can name specific columns:
CREATE TRIGGER accounts_balance_audit
AFTER UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();This trigger is considered for an UPDATE statement that names balance in its SET list. It does not run for an update that names only email.
The column list does not test whether the value actually changed. This statement still qualifies:
UPDATE accounts
SET balance = balance
WHERE id = 42;Use a WHEN condition when you need to test the resulting values.
Filter rows with `WHEN`
A WHEN condition is a Boolean expression that decides whether PostgreSQL calls the trigger function for a row-level trigger. OLD contains the previous row, and NEW contains the proposed or final row, depending on trigger timing.
CREATE TRIGGER accounts_balance_changed
AFTER UPDATE OF balance ON accounts
FOR EACH ROW
WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
EXECUTE FUNCTION audit_accounts();IS DISTINCT FROM compares values safely when either value can be NULL. Unlike <>, it treats NULL as a comparable value.
A WHEN condition does not replace a validation rule. It only skips the function when the condition is false. A BEFORE trigger can change NEW, and an AFTER trigger observes the completed row.
Common boundaries
WHEN conditions belong to row-level triggers. A statement-level trigger runs once for the whole statement and has no single NEW or OLD row to test. Use a transition table when a statement-level trigger needs the affected rows.
A condition cannot contain a subquery. For complex checks, keep the trigger selection simple and perform the additional query inside the trigger function, or use a constraint when the rule can be expressed declaratively.
Exercise
Will an AFTER UPDATE OF email trigger run for UPDATE accounts SET balance = 10 WHERE id = 1?
Show answer
No. The statement does not name email in its SET list.