Sub topic 14
When several triggers fire on the same event
This chapter assumes you can write a trigger function and attach it with CREATE TRIGGER. You should also know the difference between BEFORE and AFTER timing and between row-level and statement-level triggers. Here you will learn how PostgreSQL orders triggers when more than one applies to the same statement, and how to design for that order.
The four phases
A single INSERT, UPDATE, or DELETE can match many triggers. PostgreSQL runs them in a fixed sequence of phases:
- BEFORE statement-level triggers, once, before any row is touched.
- BEFORE row-level triggers, once per affected row, just before that row is written.
- AFTER row-level triggers, once per affected row, after the whole statement has finished.
- AFTER statement-level triggers, once, at the very end.
Within one phase, triggers fire in alphabetical order by trigger name. PostgreSQL does not use the order in which you created them.
Seeing the order
This script creates one trigger for each phase. It creates the two BEFORE row triggers in reverse alphabetical order on purpose.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL
);
CREATE FUNCTION trace_row() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE '% (% ROW) status=%', TG_NAME, TG_WHEN, NEW.status;
RETURN NEW;
END;
$$;
CREATE FUNCTION trace_stmt() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE '% (% STATEMENT)', TG_NAME, TG_WHEN;
RETURN NULL;
END;
$$;
CREATE TRIGGER b_stmt BEFORE INSERT ON orders
FOR EACH STATEMENT EXECUTE FUNCTION trace_stmt();
CREATE TRIGGER b_row_2 BEFORE INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION trace_row();
CREATE TRIGGER b_row_1 BEFORE INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION trace_row();
CREATE TRIGGER a_row AFTER INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION trace_row();
CREATE TRIGGER a_stmt AFTER INSERT ON orders
FOR EACH STATEMENT EXECUTE FUNCTION trace_stmt();
INSERT INTO orders (status) VALUES ('new'), ('paid');The notices appear in this order:
NOTICE: b_stmt (BEFORE STATEMENT)
NOTICE: b_row_1 (BEFORE ROW) status=new
NOTICE: b_row_2 (BEFORE ROW) status=new
NOTICE: b_row_1 (BEFORE ROW) status=paid
NOTICE: b_row_2 (BEFORE ROW) status=paid
NOTICE: a_row (AFTER ROW) status=new
NOTICE: a_row (AFTER ROW) status=paid
NOTICE: a_stmt (AFTER STATEMENT)Three details matter here:
b_row_1fires beforeb_row_2even though it was created later.- Both BEFORE row triggers finish for the first row before the second row starts.
- No AFTER row trigger runs until both rows are written, because PostgreSQL queues AFTER row events and fires them at the end of the statement. Inside an AFTER row trigger, the whole statement's changes are therefore visible.
Triggers hand the row down the chain
Ordering matters most among BEFORE row triggers. Each one receives, as NEW, the row returned by the previous one. If one trigger changes a column, the next trigger sees the changed value.
CREATE FUNCTION normalize_status() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.status := lower(btrim(NEW.status));
RETURN NEW;
END;
$$;
CREATE FUNCTION validate_status() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.status NOT IN ('new', 'paid', 'shipped') THEN
RAISE EXCEPTION 'invalid status: %', NEW.status
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER orders_10_normalize
BEFORE INSERT OR UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION normalize_status();
CREATE TRIGGER orders_20_validate
BEFORE INSERT OR UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION validate_status();Inserting ' PAID ' now succeeds, because normalization runs first. If you swapped the numeric prefixes, validation would see the untrimmed text and reject the row.
If any BEFORE row trigger returns NULL, PostgreSQL skips the operation for that row. It also does not fire the remaining BEFORE row triggers for it, and it fires no AFTER row triggers for it. An exception aborts the whole statement.
Controlling the order with names
Because name order is the only control you have, adopt a naming convention. A numeric prefix is common, as in orders_10_normalize and orders_20_validate.
- Names compare byte by byte, not as numbers, so
trg_10sorts beforetrg_2. Zero-pad or use fixed-width prefixes. - The comparison does not depend on your database's collation. Uppercase letters sort before lowercase ones.
- To change the order, rename a trigger without dropping it:
ALTER TRIGGER orders_20_validate ON orders
RENAME TO orders_05_validate;WHEN conditions and the chain
A WHEN condition on a BEFORE row trigger is evaluated just before that trigger would run. It sees NEW as modified by earlier triggers in the chain. A WHEN condition on an AFTER row trigger is evaluated right after the row is written, and it decides whether the event is queued at all.
CREATE TRIGGER orders_30_notify_shipped
BEFORE UPDATE ON orders
FOR EACH ROW
WHEN (NEW.status = 'shipped')
EXECUTE FUNCTION trace_row();If orders_10_normalize turns 'SHIPPED' into 'shipped', this condition matches. The comparison would fail if the normalizing trigger fired later.
Gotchas
- Triggers on different events do not interact by order. A trigger defined
BEFORE INSERTand one definedBEFORE UPDATEnever compete. A trigger declared forINSERT OR UPDATEtakes part in the ordering for each event separately. - Writes from a trigger start a new cycle. If a trigger function updates another table, that statement runs its own BEFORE, row, and AFTER phases to completion before your trigger function returns. Nested firing is covered in the chapter on recursion.
- Statement-level triggers always fire. They run even when the statement affects zero rows. Row-level triggers do not.
- Do not rely on creation order or on a clever name for correctness. If two triggers must run in a strict order, add a comment saying so. Better still, combine them into one function whose body states the order.
- Order within AFTER row triggers rarely matters for data. Each one sees the final table state, so they are usually independent. They matter when one AFTER trigger writes something that another reads.
Exercise
A table has three BEFORE INSERT FOR EACH ROW triggers named audit_stamp, Validate_row, and check_amount, plus an AFTER INSERT FOR EACH STATEMENT trigger named aaa_summary. In what order do they fire for a statement that inserts one row?
Show answer
Validate_row, audit_stamp, check_amount, then aaa_summary. BEFORE row triggers run in byte-wise name order, and the uppercase "V" sorts before the lowercase letters, so Validate_row is first. Then audit_stamp comes before check_amount. The AFTER statement trigger always runs last, whatever its name.