Sub topic 2
Choosing Events, UPDATE OF Columns, and WHEN Conditions
This chapter assumes you know basic SQL, can write a CREATE TABLE statement, and have seen a simple PL/pgSQL function. The examples use this table:
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()
);Choosing events
A trigger fires on one or more of INSERT, UPDATE, DELETE, and TRUNCATE. List several events with OR. Include only the events you need, because each one adds work to every matching statement.
UPDATE OF columns
UPDATE OF balance fires only when an UPDATE statement names balance in its SET list. It fires even when the new value equals the old one. Use it to skip updates to unrelated columns.
WHEN conditions
A WHEN clause is a test that PostgreSQL evaluates before it calls the trigger function. If the test is false, the function does not run. Row-level triggers can refer to OLD and NEW in the WHEN clause.
Reading NEW, OLD, and TG_* variables
Inside a row-level trigger function:
- NEW holds the row after the change. It is set for INSERT and UPDATE, and NULL for DELETE.
- OLD holds the row before the change. It is set for UPDATE and DELETE, and NULL for INSERT.
- TG_OP holds the event name: 'INSERT', 'UPDATE', 'DELETE', or 'TRUNCATE'.
- TGTABLENAME holds the name of the table that fired the trigger.
What the return value does
In a BEFORE row trigger, RETURN NEW lets the operation continue, using any changes you made to NEW. RETURN NULL skips the change for that row. AFTER row triggers and statement-level triggers ignore their return value, so they return NULL.
Example: keeping updated_at current
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();The WHEN clause skips the function when an UPDATE changes no column values.
Example: rejecting bad data
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();RAISE EXCEPTION aborts the statement and rolls back its changes.
Example: an audit trail
CREATE TABLE accounts_audit (
audit_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL,
operation text NOT NULL,
old_row jsonb,
new_row jsonb,
changed_at timestamptz NOT NULL DEFAULT now(),
changed_by text NOT NULL DEFAULT current_user
);
CREATE FUNCTION audit_accounts() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO accounts_audit (account_id, operation, new_row)
VALUES (NEW.id, TG_OP, to_jsonb(NEW));
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO accounts_audit (account_id, operation, old_row, new_row)
VALUES (NEW.id, TG_OP, to_jsonb(OLD), to_jsonb(NEW));
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO accounts_audit (account_id, operation, old_row)
VALUES (OLD.id, TG_OP, to_jsonb(OLD));
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();Exercise
Given the accountssetupdatedat trigger above, what happens to updatedat when you run UPDATE accounts SET balance = balance WHERE id = 1?
Show answer
No column value changes, so the WHEN test (OLD. IS DISTINCT FROM NEW.) is false. PostgreSQL skips the function, and updated_at keeps its old value.