Sub topic 13
Transition tables for set-based statement triggers
This chapter assumes you can write a PL/pgSQL trigger function, attach it with CREATE TRIGGER, and tell FOR EACH ROW from FOR EACH STATEMENT. It also assumes you know that row triggers see NEW and OLD, and statement triggers do not. Transition tables need PostgreSQL 10 or later.
The problem transition tables solve
A statement-level trigger fires once per statement, however many rows the statement changes. It has no NEW or OLD, because there is no single row to point at. Before PostgreSQL 10, a statement trigger could not see which rows had changed.
The usual workaround was a row-level trigger. A DELETE of 50,000 rows then made 50,000 function calls, and each call ran its own small INSERT into a log table.
A transition table fixes this. It is a read-only temporary relation that holds every row the statement affected, and the trigger function queries it with ordinary SQL. The function runs once and does its work as one set operation.
The REFERENCING clause of CREATE TRIGGER declares the tables:
OLD TABLE AS nameholds the rows as they were before the statement. It is available forUPDATEandDELETE.NEW TABLE AS nameholds the rows as they are after the statement. It is available forINSERTandUPDATE.
How the data flows
The trigger fires after the statement has finished changing rows. That is why transition tables work only with AFTER triggers.
Example 1: count deleted rows
This is the smallest useful case. The function counts the rows in the transition table and reports the number.
CREATE TABLE IF NOT EXISTS 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 log_bulk_deletes() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
n bigint;
BEGIN
SELECT count(*) INTO n FROM deleted_rows;
RAISE NOTICE '% rows deleted from %', n, TG_TABLE_NAME;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_bulk_delete
AFTER DELETE ON accounts
REFERENCING OLD TABLE AS deleted_rows
FOR EACH STATEMENT
EXECUTE FUNCTION log_bulk_deletes();Test it:
INSERT INTO accounts (email)
SELECT 'user' || g || '@example.com' FROM generate_series(1, 1000) AS g;
DELETE FROM accounts WHERE id <= 500;
-- NOTICE: 500 rows deleted from accountsThe name deleted_rows is local to this trigger. You choose it, and the function body refers to it like a table. It does not appear in any schema. The function returns NULL because the return value of an AFTER statement trigger is ignored.
Example 2: set-based change log with OLD and NEW
An UPDATE trigger can declare both tables. This function logs every balance change with one INSERT ... SELECT.
CREATE TABLE accounts_balance_log (
log_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL,
old_balance numeric(12,2) NOT NULL,
new_balance numeric(12,2) NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION log_balance_changes() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO accounts_balance_log (account_id, old_balance, new_balance)
SELECT n.id, o.balance, n.balance
FROM old_rows AS o
JOIN new_rows AS n ON n.id = o.id
WHERE o.balance IS DISTINCT FROM n.balance;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_balance_log_trg
AFTER UPDATE ON accounts
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT
EXECUTE FUNCTION log_balance_changes();Two details matter here:
- The two transition tables have no built-in pairing. Nothing says that the third row of
old_rowsmatches the third row ofnew_rows. You must join them on a unique key, here the primary keyid. If the table has no key, you cannot reliably pair old and new versions. - The
WHEREclause filters out rows whose balance did not change. Without it, an update that touched onlyemailwould also be logged.
Run UPDATE accounts SET balance = balance + 10; on 500 rows and the log table receives 500 rows from a single function call.
Restrictions
The one-event rule has a practical consequence. To audit inserts, updates, and deletes set-wise, you create three triggers. They can share one function only if the function does not depend on which table names exist, so most people write three small functions.
The table names are also tied to the event. OLD TABLE is valid only for triggers that fire on UPDATE or DELETE, and NEW TABLE only for INSERT or UPDATE. A WHEN condition is not allowed to look at the rows of a statement trigger, because it has no row to test.
Edge cases and costs
- Zero rows. A statement trigger fires even when the statement matched no rows. The transition tables are then empty, so a
SELECT count(*)returns 0. Guard withIF EXISTS (SELECT 1 FROM new_rows)if you want to skip empty work. - Row-level triggers can use them too.
FOR EACH ROWwithREFERENCINGis allowed. The function runs once per row, and each call sees the full transition table for the statement. That gives you the cost of row triggers with no benefit, so useFOR EACH STATEMENT. - Memory. PostgreSQL keeps the transition data in a tuplestore. It stays in memory up to
work_memand then spills to temporary files. A statement that changes millions of rows therefore adds I/O, and the extra data is held until the statement's triggers finish. - No modification. You cannot change a transition table. A statement trigger cannot alter the rows already written, so use a
BEFORErow trigger for that. INSERT ... ON CONFLICT DO UPDATE. This statement fires both theINSERTand theUPDATEstatement triggers. Each trigger sees only the rows that went through its own path.
When to choose them
Use transition tables when the work per statement can be written as a single set-based query. Examples are bulk audit logging, maintaining summary or counter tables, and checking an invariant across all changed rows. Stay with row-level triggers when each row needs its own decision, or when you must modify the row being written.
Exercise
You want a trigger that writes one log row for every inserted account, and you want it to run once per INSERT statement. A colleague writes CREATE TRIGGER t AFTER INSERT OR UPDATE ON accounts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION f(); and it fails. Why does it fail, and what is the corrected trigger for the insert case?
Show answer
PostgreSQL does not allow transition tables on a trigger that fires on more than one event. Split the trigger by event. For inserts: CREATE TRIGGER t_ins AFTER INSERT ON accounts REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION f();. The function can then run INSERT INTO accounts_audit (account_id, operation, new_row) SELECT id, 'INSERT', to_jsonb(n) FROM new_rows AS n;. Use a separate AFTER UPDATE trigger with OLD TABLE and NEW TABLE for updates.