Sub topic 14
When several triggers fire on the same event
This chapter assumes basic INSERT, UPDATE, and CREATE TABLE syntax, familiarity with PostgreSQL clients, and a basic understanding of transactions.
A PostgreSQL trigger runs a trigger function when a specified database event occurs. One table can have several triggers for the same event. PostgreSQL determines their order from both their timing and their names.
The execution sequence
For a data-change statement, PostgreSQL generally follows this sequence:
- Fire
BEFORE STATEMENTtriggers. - For each affected row, fire
BEFORE ROWtriggers. - Perform the insert, update, or delete.
- For each affected row, fire
AFTER ROWtriggers. - Fire
AFTER STATEMENTtriggers.
Triggers with the same event, timing, and level fire in alphabetical order by trigger name. This order is based on the trigger names, not on the order of the CREATE TRIGGER statements.
Changes made by earlier triggers
A BEFORE ROW trigger can change NEW. A later BEFORE ROW trigger sees that changed record. This makes trigger names part of the behavior of your schema.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price numeric(10, 2) NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION normalize_product() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.name := trim(NEW.name);
RETURN NEW;
END;
$$;
CREATE FUNCTION set_product_timestamp() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER a_normalize_product
BEFORE INSERT OR UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION normalize_product();
CREATE TRIGGER b_set_product_timestamp
BEFORE INSERT OR UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION set_product_timestamp();Here, a_normalize_product runs before b_set_product_timestamp because a sorts before b. Renaming either trigger can change the order. Use clear names that express a deliberate ordering convention, such as a_validate, b_derive, and c_audit.
Common ordering errors
An AFTER trigger cannot change the row that was already written. Its return value is ignored. A BEFORE trigger that returns NULL cancels the operation for that row, so later row-level triggers and the table operation do not run for that row.
An AFTER trigger on one table can cause triggers on another table through a cascading foreign-key action or a trigger-issued statement. Those nested operations have their own order. Do not assume that all triggers across the database form one alphabetical sequence.
Constraint triggers can be deferred until transaction commit. Their checks therefore may run after ordinary AFTER triggers.
Exercise
Two BEFORE UPDATE row-level triggers are named audit_change and validate_change. Which runs first, and can the second trigger see changes made by the first?
Show answer
audit_change runs first because trigger names are compared alphabetically. The second trigger can see changes that the first trigger made to NEW.