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.
| seqint4 | trigger_whentext | leveltext | accountint4 |
|---|---|---|---|
| 1 | BEFORE | STATEMENT | null |
| 2 | BEFORE | ROW | 1 |
| 3 | BEFORE | ROW | 2 |
| 4 | BEFORE | ROW | 3 |
| 5 | AFTER | ROW | 1 |
| 6 | AFTER | ROW | 2 |
| 7 | AFTER | ROW | 3 |
| 8 | AFTER | STATEMENT | null |
-- 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:
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();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.
| idint4 | account_idint4 | optext | old_balancenumeric | new_balancenumeric |
|---|
the audit table starts empty.
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;| idint4 | account_idint4 | optext | old_balancenumeric | new_balancenumeric |
|---|---|---|---|---|
| 1 | 1 | UPDATE | 100.00 | 50.00 |
| 2 | 2 | UPDATE | 100.00 | 150.00 |
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:
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;| idint4 | balancenumeric | versionint4 |
|---|---|---|
| 1 | 90.00 | 1 |
| idint4 | ownertext | versionint4 |
|---|---|---|
| 1 | Alice | 1 |
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.
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;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:
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;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:
- 1CREATE SEQUENCE trigger_calls;
- 2CREATE TABLE transfers_audit (transfer_id bigint, old_amount numeric(12,2), new_amount numeric(12,2));
- 3CREATE FUNCTION audit_transfer_row() RETURNS trigger LANGUAGE plpgsql AS $$
- 4BEGIN
- 5 PERFORM nextval('trigger_calls');
- 6 INSERT INTO transfers_audit VALUES (OLD.id, OLD.amount, NEW.amount);
- 7 RETURN NULL;
- 8END $$;
- 9CREATE TRIGGER audit_transfers AFTER UPDATE ON transfers
- 10FOR EACH ROW EXECUTE FUNCTION audit_transfer_row();
- 11UPDATE transfers SET amount = amount + 1;
- 12SELECT nextval('trigger_calls') - 1 AS calls, (SELECT count(*) FROM transfers_audit) AS audit_rows;
| callsint8 | audit_rowsint8 |
|---|---|
| 20000 | 20000 |
the trigger function ran 20,000 times, and ran 20,000 single-row INSERTs.
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:
| idint4 | currencybpchar | ctidtid | xminxid |
|---|---|---|---|
| 1 | EUR | (9,49) | 800 |
| 2 | EUR | (9,50) | 800 |
| 4 | EUR | (0,4) | 752 |
three accounts: where each version lives (ctid) and which transaction wrote it (xmin).
CREATE TRIGGER skip_noop BEFORE UPDATE ON accounts
FOR EACH ROW EXECUTE FUNCTION suppress_redundant_updates_trigger();
UPDATE accounts SET currency = currency;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.