skip to content

triggers

code that runs on every INSERT, UPDATE or DELETE. BEFORE vs AFTER, row vs statement, and an audit table.

address
everything.writes.triggers
part
part 5, changing data
chapter
chapter 10 of 10
reading time
9 min

a trigger runs a function automatically when rows are inserted, updated or deleted. BEFORE row triggers run before each row is written and can change it (through NEW) or skip it. AFTER triggers run once the change is made, and see OLD and NEW as they ended up.

a row trigger fires once per row: 20,000 times for a 20,000-row UPDATE. a statement trigger fires once, and with transition tables it still sees every row.

the picture

you know the rule that has to hold no matter who changes the table: every balance change gets an audit row, every updated row gets its version bumped, nothing with money in it gets deleted? you can remember to do it in every code path, or the database can do it for you, every time, whichever path the change came from. that's a trigger.

think of a tripwire on a door. you don't call it, you walk through the door and it goes off. a BEFORE trigger is a guard who checks your bag before you go in (and can take things out, or turn you away). an AFTER trigger is the camera that records what happened once you're through.

hover a stage.

seqint4trigger_whentextleveltextaccountint4
1BEFORESTATEMENTnull
2BEFOREROW1
3BEFOREROW2
4BEFOREROW3
5AFTERROW1
6AFTERROW2
7AFTERROW3
8AFTERSTATEMENTnull
(8 rows)
real output, postgres 18.6 (PGlite 0.5.12) · triggers
four triggers on bank's accounts, one of each kind, all writing to one log. one UPDATE of three rows, and the log of what fired, in order. each BEFORE ROW trigger fires as its row is written; every AFTER ROW trigger waits until the statement has done all its rows.
predict the output
sql
-- one UPDATE touches accounts 1 and 2.
-- after BEFORE ROW fires for account 1 and account 1 is written,
-- which trigger fires next?

every block below starts from a fresh copy of bank, so nothing you do here sticks.

an audit table

the classic first trigger. a table to write to, a function that returns trigger, and the trigger that ties the function to the table and its events:

audit.sqldb=bank · session audit
CREATE TABLE accounts_audit (
  id          int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id  int NOT NULL,
  op          text NOT NULL,
  old_balance numeric(12,2),
  new_balance numeric(12,2)
);
 
CREATE FUNCTION audit_accounts() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'DELETE' THEN
    INSERT INTO accounts_audit (account_id, op, old_balance) VALUES (OLD.id, TG_OP, OLD.balance);
  ELSIF TG_OP = 'INSERT' THEN
    INSERT INTO accounts_audit (account_id, op, new_balance) VALUES (NEW.id, TG_OP, NEW.balance);
  ELSE
    INSERT INTO accounts_audit (account_id, op, old_balance, new_balance) VALUES (NEW.id, TG_OP, OLD.balance, NEW.balance);
  END IF;
  RETURN NULL;
END $$;
 
CREATE TRIGGER audit AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW EXECUTE FUNCTION audit_accounts();
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE FUNCTION
#3 · CREATE TRIGGER

inside a trigger function, NEW is the row being written (INSERT and UPDATE), OLD the row as it was (UPDATE and DELETE), and TG_OP, TG_WHEN, TG_LEVEL and TG_TABLE_NAME say why it's running. an AFTER row trigger's return value is ignored, so RETURN NULL is the convention.

before anything runs
accounts_audit, after this step
accounts_audit after: empty
idint4account_idint4optextold_balancenumericnew_balancenumeric
(0 rows)
new row

the audit table starts empty.

step 1/4
real output, postgres 18.6 (PGlite 0.5.12) · triggers
the audit table after three ordinary statements on accounts. none of them mentions accounts_audit. the transfer updates two rows and gets two audit rows. a DELETE has no new balance, an INSERT no old one.
sqldb=bank · session audit
continues session audit (1 earlier block run first)
UPDATE accounts SET balance = balance + CASE id WHEN 1 THEN -50.00 ELSE 50.00 END
WHERE id IN (1, 2);
 
SELECT * FROM accounts_audit ORDER BY id;
output, from postgres 18.6
#1 · UPDATE 2
#2 · SELECT 2
idint4account_idint4optextold_balancenumericnew_balancenumeric
11UPDATE100.0050.00
22UPDATE100.00150.00
(2 rows)

the audit rows are written in the same transaction as the change. roll the transfer back and its audit rows go too. that's the point: the audit can't disagree with the data. (keeping history properly, as of any date, is a design question of its own: history, audit and soft delete.)

BEFORE triggers change the row

a BEFORE row trigger runs before the row is written and returns the row to write. change NEW and you change what goes in. bank's accounts have a version column for optimistic locking; a trigger can bump it so no code path forgets. and WHEN makes the trigger fire only when it matters:

sqldb=bank · session version
CREATE FUNCTION bump_version() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.version := OLD.version + 1;
  RETURN NEW;
END $$;
 
CREATE TRIGGER bump BEFORE UPDATE ON accounts
FOR EACH ROW WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
EXECUTE FUNCTION bump_version();
 
UPDATE accounts SET balance = balance - 10 WHERE id = 1 RETURNING id, balance, version;
UPDATE accounts SET owner = 'Alice' WHERE id = 1 RETURNING id, owner, version;
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · CREATE TRIGGER
#3 · UPDATE 1
idint4balancenumericversionint4
190.001
(1 row)
#4 · UPDATE 1
idint4ownertextversionint4
1Alice1
(1 row)

version 1 after the balance changed, still 1 after the rename: the WHEN condition was false, so the trigger didn't even run. RETURNING shows the row after BEFORE triggers changed it, which makes it the easy way to see what a trigger did (RETURNING).

a BEFORE trigger can also say no: return NULL to skip the row silently, or raise an error to stop the whole statement.

sqldb=bank
CREATE FUNCTION keep_funded() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF OLD.balance <> 0 THEN
    RAISE EXCEPTION 'account % still holds %', OLD.id, OLD.balance;
  END IF;
  RETURN OLD;
END $$;
 
CREATE TRIGGER keep_funded BEFORE DELETE ON accounts
FOR EACH ROW EXECUTE FUNCTION keep_funded();
 
DELETE FROM accounts WHERE id = 1;
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · CREATE TRIGGER
#3 · ERROR P0001
ERROR P0001: account 1 still holds 100.00
CONTEXT: PL/pgSQL function keep_funded() line 4 at RAISE

one row at a time adds up

a row trigger is called once per row, and whatever it does, it does once per row. bank's transfers table has 20,000 rows. touch all of them with a row-level audit trigger, and postgres says exactly how many times it ran:

sqldb=bank
CREATE TABLE transfers_audit (transfer_id bigint, old_amount numeric(12,2), new_amount numeric(12,2));
CREATE FUNCTION audit_transfer_row() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO transfers_audit VALUES (OLD.id, OLD.amount, NEW.amount);
  RETURN NULL;
END $$;
CREATE TRIGGER audit_transfers AFTER UPDATE ON transfers
FOR EACH ROW EXECUTE FUNCTION audit_transfer_row();
 
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, COSTS OFF, BUFFERS OFF)
UPDATE transfers SET amount = amount + 1;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE FUNCTION
#3 · CREATE TRIGGER
#4 · EXPLAIN
Update on transfers (actual rows=0.00 loops=1) -> Seq Scan on transfers (actual rows=20000.00 loops=1) Trigger audit_transfers: calls=20000

Trigger audit_transfers: calls=20000. twenty thousand function calls, each running its own single-row INSERT. a statement-level trigger runs once instead, and since it has no single NEW or OLD, REFERENCING hands it the statement's rows as two tables, the transition tables:

trigger =
audit_transfers.sql
  1. 1CREATE SEQUENCE trigger_calls;
  2. 2CREATE TABLE transfers_audit (transfer_id bigint, old_amount numeric(12,2), new_amount numeric(12,2));
  3. 3CREATE FUNCTION audit_transfer_row() RETURNS trigger LANGUAGE plpgsql AS $$
  4. 4BEGIN
  5. 5 PERFORM nextval('trigger_calls');
  6. 6 INSERT INTO transfers_audit VALUES (OLD.id, OLD.amount, NEW.amount);
  7. 7 RETURN NULL;
  8. 8END $$;
  9. 9CREATE TRIGGER audit_transfers AFTER UPDATE ON transfers
  10. 10FOR EACH ROW EXECUTE FUNCTION audit_transfer_row();
  11. 11UPDATE transfers SET amount = amount + 1;
  12. 12SELECT nextval('trigger_calls') - 1 AS calls, (SELECT count(*) FROM transfers_audit) AS audit_rows;
the result for FOR EACH ROW
callsint8audit_rowsint8
2000020000
(1 row)

the trigger function ran 20,000 times, and ran 20,000 single-row INSERTs.

real output, postgres 18.6 (PGlite 0.5.12) · triggers
the same 20,000-row UPDATE with the same audit, as a row trigger and as a statement trigger with transition tables. both write 20,000 audit rows. one calls its function 20,000 times, the other once.

one INSERT ... SELECT of 20,000 rows instead of 20,000 INSERTs of one: the same difference as COPY against single inserts, inside the database. transition tables work for AFTER triggers only, and are the way to write anything that summarizes a statement (a running total, a count per account) without a call per row.

the UPDATE that changes nothing

UPDATE accounts SET currency = currency changes no values. it still writes a complete new version of every row it touches, with a new address and a new xmin, because in postgres an UPDATE is an INSERT of a new version. that's work for the table, its indexes, the WAL and later VACUUM, for nothing. postgres ships a trigger function to skip it:

before anything runs
accounts, 3 of 1,000, after this step
accounts, 3 of 1,000 after: before
idint4currencybpcharctidtidxminxid
1EUR(9,49)800
2EUR(9,50)800
4EUR(0,4)752
(3 rows)
changed

three accounts: where each version lives (ctid) and which transaction wrote it (xmin).

step 1/5
real output, postgres 18.6 (PGlite 0.5.12) · triggers
three accounts, with each version's address (ctid) and the transaction that wrote it (xmin). the no-op UPDATE rewrites every row, so both change. with suppress_redundant_updates_trigger() in place, the same UPDATE says UPDATE 0 and writes nothing. a real change still goes through.
sqldb=bank
CREATE TRIGGER skip_noop BEFORE UPDATE ON accounts
FOR EACH ROW EXECUTE FUNCTION suppress_redundant_updates_trigger();
 
UPDATE accounts SET currency = currency;
output, from postgres 18.6
#1 · CREATE TRIGGER
#2 · UPDATE 0

the trigger compares the new row with the old one, byte for byte, and returns NULL when they're identical, so the row is skipped. the manual suggests naming it so it sorts after your other BEFORE triggers (they fire in name order), so it sees the row they produced. it's not free either: it compares every row. it pays off when no-op updates are common, like an ORM that writes every column back whether it changed or not.

keylines

  • a trigger runs a function on INSERT, UPDATE or DELETE, whichever code path made the change.
  • BEFORE row triggers can change NEW or skip the row. AFTER triggers see the final rows.
  • AFTER row triggers are queued and fire once the statement has done all its rows.
  • a row trigger fires once per row. a statement trigger with transition tables fires once.
  • a no-op UPDATE still writes new versions. suppress_redundant_updates_trigger() skips them.