Sub topic 13
Writing trigger functions
This chapter assumes you can write a basic PL/pgSQL function, use IF and RAISE, and run SQL in psql. It covers how trigger functions differ from ordinary functions, which special variables they receive, and the errors that come up most often. The target length is about 1,400 words.
What a trigger is
A trigger is a rule that tells PostgreSQL to run a function automatically when a table changes. You write two pieces:
- A trigger function. It takes no arguments in its declaration and returns the pseudo-type
trigger. - A
CREATE TRIGGERstatement. It attaches the function to a table and says when it fires.
The split lets you reuse one function on many tables. The function is a normal PL/pgSQL function, but PostgreSQL fills in special variables before it runs.
A first trigger: stamping updated_at
This example assumes orders has an updated_at timestamptz column.
CREATE FUNCTION set_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_orders_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();NEW is the row as it will be written. Because the trigger fires BEFORE, changes to NEW are stored. Returning NEW tells PostgreSQL to continue with that row.
The special variables
PostgreSQL creates these variables automatically inside a trigger function.
| Variable | Type | Meaning |
|---|---|---|
| `NEW` | record | The new row. Set for `INSERT` and `UPDATE` row triggers. Unassigned for `DELETE` and for statement-level triggers. |
| `OLD` | record | The old row. Set for `UPDATE` and `DELETE` row triggers. Unassigned for `INSERT`. |
| `TG_OP` | text | `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`. |
| `TG_WHEN` | text | `BEFORE`, `AFTER`, or `INSTEAD OF`. |
| `TG_LEVEL` | text | `ROW` or `STATEMENT`. |
| `TG_TABLE_NAME` | name | The table that fired the trigger. |
| `TG_TABLE_SCHEMA` | name | The schema of that table. |
| `TG_NARGS`, `TG_ARGV[]` | integer, text[] | Count and values of arguments given in `CREATE TRIGGER`. |
Reading OLD in an INSERT trigger is an error in current PostgreSQL versions, so check TG_OP first when one function serves several events.
Timing and level
Two choices define when a trigger runs.
- Timing:
BEFOREruns ahead of the write. It can change the row or cancel the operation.AFTERruns once the row is written. It sees the final data and suits auditing and side effects.INSTEAD OFapplies only to views. - Level:
FOR EACH ROWruns once per affected row.FOR EACH STATEMENTruns once per statement, even if zero rows changed.
In practice AFTER ROW triggers are queued and run at the end of the statement, after all rows are written. The diagram shows the order, not exact timing.
Return values
What you return matters, and it depends on timing and level.
BEFORE ... FOR EACH ROW: return a row to continue with it, usuallyNEW. ReturnNULLto skip the operation for that row, with no error. ForDELETE, returnOLD, becauseNEWis not set.AFTERrow triggers and all statement-level triggers: the return value is ignored. ReturningNULLis conventional.- Raising an exception aborts the statement and rolls back its changes.
A common bug is a BEFORE DELETE trigger that ends with RETURN NEW. NEW is null there, so every delete is silently skipped.
Using NEW, OLD, and TG_OP together
One function can handle several events by branching on TG_OP. This audit example assumes an orders_audit table with the columns shown.
CREATE TABLE orders_audit (
audit_id bigserial PRIMARY KEY,
operation text NOT NULL,
order_id integer NOT NULL,
old_total numeric,
new_total numeric,
changed_at timestamptz NOT NULL DEFAULT now(),
changed_by text NOT NULL DEFAULT current_user
);
CREATE FUNCTION audit_orders()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO orders_audit (operation, order_id, new_total)
VALUES (TG_OP, NEW.id, NEW.total);
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO orders_audit (operation, order_id, old_total, new_total)
VALUES (TG_OP, NEW.id, OLD.total, NEW.total);
RETURN NEW;
ELSE
INSERT INTO orders_audit (operation, order_id, old_total)
VALUES (TG_OP, OLD.id, OLD.total);
RETURN OLD;
END IF;
END;
$$;
CREATE TRIGGER trg_orders_audit
AFTER INSERT OR UPDATE OR DELETE ON orders
FOR EACH ROW
EXECUTE FUNCTION audit_orders();The trigger is AFTER because it records what was actually stored. The return values do not affect an AFTER trigger, but returning the correct row keeps the function safe if someone later changes it to BEFORE.
Validation with BEFORE triggers
A BEFORE trigger can reject or repair data before it is stored.
CREATE FUNCTION check_order_total()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.total < 0 THEN
RAISE EXCEPTION 'order % has a negative total: %', NEW.id, NEW.total
USING ERRCODE = 'check_violation';
END IF;
NEW.total := round(NEW.total, 2);
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_orders_check_total
BEFORE INSERT OR UPDATE ON orders
FOR EACH ROW
EXECUTE FUNCTION check_order_total();Prefer a CHECK constraint for a simple rule like this one, because the planner and other tools can see it. Use a trigger when the rule needs a lookup in another table or has to modify the row.
Conditional firing with WHEN and UPDATE OF
Firing a function for every row costs time. Narrow the trigger in CREATE TRIGGER.
CREATE TRIGGER trg_orders_total_changed
AFTER UPDATE OF total ON orders
FOR EACH ROW
WHEN (OLD.total IS DISTINCT FROM NEW.total)
EXECUTE FUNCTION audit_orders();UPDATE OF total fires only when total appears in the statement's SET list. WHEN checks the condition before the function is called, so unchanged rows never pay the call cost. Use IS DISTINCT FROM so that NULL values compare correctly.
Passing arguments
Arguments go in the CREATE TRIGGER call and arrive as text in TG_ARGV. The function declaration still has an empty parameter list.
CREATE FUNCTION stamp_column()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_NARGS <> 1 THEN
RAISE EXCEPTION 'stamp_column needs one argument: the column name';
END IF;
NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_orders_stamp
BEFORE UPDATE ON orders
FOR EACH ROW
EXECUTE FUNCTION stamp_column('updated_at');PL/pgSQL cannot write NEW.<name> with a name held in a variable. The jsonb_populate_record call is a standard workaround. It builds a new row of the same type with the named field replaced.
Statement-level triggers and transition tables
A statement-level AFTER trigger can read every changed row through a transition table. This avoids firing the function once per row.
CREATE FUNCTION log_bulk_delete()
RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
v_count bigint;
BEGIN
SELECT count(*) INTO v_count FROM deleted_rows;
RAISE NOTICE '% rows deleted from %', v_count, TG_TABLE_NAME;
RETURN NULL;
END;
$$;
CREATE TRIGGER trg_orders_bulk_delete
AFTER DELETE ON orders
REFERENCING OLD TABLE AS deleted_rows
FOR EACH STATEMENT
EXECUTE FUNCTION log_bulk_delete();deleted_rows behaves like a read-only table that holds the old rows. Transition tables are available only for AFTER triggers, and one trigger cannot combine transition tables with multiple events in a single definition.
Common errors and gotchas
- Wrong return on BEFORE DELETE. Return
OLD, notNEW. - Returning NULL by accident in a BEFORE row trigger. The row is skipped without any message. Make sure every code path returns a row.
- Infinite recursion. A trigger on
ordersthat updatesordersfires itself again. Guard with aWHENclause or checkpg_trigger_depth(). - Trigger order. Several triggers of the same kind on one table run in alphabetical order by name. Name them with that in mind.
- Changing NEW in an AFTER trigger. The change is ignored, because the row is already stored.
- Cost. Row triggers run inside the statement. A slow trigger makes every write slow, and a bulk load of a million rows calls a row trigger a million times.
- Disabling.
ALTER TABLE orders DISABLE TRIGGER trg_orders_audit;turns one trigger off, for example during a data load.ENABLE TRIGGERturns it back on. Both need table ownership.
Checking your triggers
List the triggers on a table and read the definition back:
SELECT tgname, tgenabled, pg_get_triggerdef(oid) AS definition
FROM pg_trigger
WHERE tgrelid = 'orders'::regclass
AND NOT tgisinternal;Then test with real statements. Update one row and confirm updated_at changed. Update zero rows and confirm no audit row appeared. Delete a row and confirm it was actually removed.
Exercise
A BEFORE DELETE row trigger on orders ends with RETURN NEW. What happens when you run DELETE FROM orders WHERE id = 5, and how do you fix it?
Show answer
NEW is not set for DELETE, so the function returns NULL. For a BEFORE row trigger, NULL means skip the operation for that row, so the row is not deleted and no error is shown. Change the last statement to RETURN OLD.
Exercise
You want an audit row only when orders.total actually changes, and you want the function skipped for all other updates. Which two clauses of CREATE TRIGGER help, and why use IS DISTINCT FROM?
Show answer
Use UPDATE OF total to fire only when total is in the SET list, and WHEN (OLD.total IS DISTINCT FROM NEW.total) to skip rows where the value is unchanged. IS DISTINCT FROM treats NULL as a comparable value, so a change from NULL to 10 counts as a change, while OLD.total <> NEW.total would yield NULL and the trigger would not fire.