Sub topic 4
BEFORE, AFTER, and INSTEAD OF
This chapter assumes you can write a basic PL/pgSQL trigger function and attach it with CREATE TRIGGER. It also assumes you know what a transaction is. Here you will learn what the timing keyword in CREATE TRIGGER controls, which timings are allowed on which objects, and how to pick one.
What timing means
The timing keyword says when the trigger function runs relative to the operation that fired it. PostgreSQL offers three values:
BEFOREruns before the row (or statement) is written.AFTERruns after the row (or statement) has been written.INSTEAD OFruns in place of the operation. It is allowed only on views.
Timing decides three things: whether you can change the data being written, whether you can see the final result of the operation, and which kinds of objects the trigger can be attached to.
BEFORE triggers
A BEFORE row-level trigger runs before the row is stored. It receives NEW, and whatever it returns becomes the row that is written. That makes BEFORE the right place to:
- fill in or normalize column values, such as
updated_at; - reject bad data with
RAISE EXCEPTION; - silently skip a row by returning
NULL.
This is the updated_at example from the plan:
CREATE TABLE 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 set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();The function edits NEW and returns it, so the changed row is the one that reaches the table. Because the row has not been written yet, a BEFORE trigger cannot see the effects of this operation in the table. Constraints such as NOT NULL, CHECK, and unique indexes are checked after BEFORE triggers run, so a BEFORE trigger can repair a value that would otherwise fail a NOT NULL check.
A BEFORE trigger that returns NULL tells PostgreSQL to skip that row. The statement continues with other rows, and the skipped row is neither inserted, updated, nor deleted. This is a common source of "my UPDATE says 0 rows" surprises.
AFTER triggers
An AFTER trigger runs once the operation has been performed. For row-level triggers, the row is already in the table, and the trigger fires after the statement has processed all its rows. AFTER row triggers are queued and run at the end of the statement, not interleaved with each row write.
Two consequences follow:
- The trigger can see the final state, including changes made by other triggers and by the statement itself. This makes
AFTERthe right choice for audit logs and for updating other tables. - The return value of an
AFTERrow trigger is ignored. Convention isRETURN NULL. The trigger cannot change the row, but it can still abort everything by raising an exception.
Here is the audit trigger from the plan, shortened to the part that matters for timing:
CREATE TABLE accounts_audit (
audit_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL,
operation text NOT NULL,
old_row jsonb,
new_row jsonb,
changed_at timestamptz NOT NULL DEFAULT now(),
changed_by text NOT NULL DEFAULT current_user
);
CREATE FUNCTION audit_accounts() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO accounts_audit (account_id, operation, new_row)
VALUES (NEW.id, TG_OP, to_jsonb(NEW));
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO accounts_audit (account_id, operation, old_row, new_row)
VALUES (NEW.id, TG_OP, to_jsonb(OLD), to_jsonb(NEW));
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO accounts_audit (account_id, operation, old_row)
VALUES (OLD.id, TG_OP, to_jsonb(OLD));
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();Using AFTER here means the audit row records what was actually stored, after any BEFORE trigger has adjusted NEW. A BEFORE audit trigger could log a value that a later trigger then changes.
INSTEAD OF triggers
An INSTEAD OF trigger replaces the operation. It exists for views, which have no storage of their own. Without such a trigger, an INSERT into a simple join view or an aggregate view fails. With one, the function decides what the operation means, usually by writing to the underlying tables.
CREATE VIEW account_emails AS
SELECT id, email FROM accounts;
CREATE FUNCTION account_emails_insert() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO accounts (email) VALUES (NEW.email)
RETURNING id INTO NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER account_emails_ins
INSTEAD OF INSERT ON account_emails
FOR EACH ROW
EXECUTE FUNCTION account_emails_insert();Rules for INSTEAD OF:
- It is allowed only on views, and only as
FOR EACH ROW. - Returning a non-null row tells PostgreSQL the operation was handled, and it counts toward the reported row count. Returning
NULLmeans nothing was done for that row. - It cannot take a
WHENclause that refers to column values in some older uses, and it cannot useUPDATE OF columnlists. Check theCREATE TRIGGERreference for your version if you rely on these.
Which timing is allowed where
Not every combination is valid. This table summarizes it.
| Object | BEFORE | AFTER | INSTEAD OF |
|---|---|---|---|
| Table, row-level | Yes | Yes | No |
| Table, statement-level | Yes | Yes | No |
| View, row-level | No | No | Yes |
| View, statement-level | Yes | Yes | No |
| Foreign table, row-level | Yes | Yes | No |
Partitioned tables support row-level triggers on the parent in recent versions, but BEFORE row triggers on a partitioned table have restrictions about moving rows between partitions. Test these cases on your version.
Choosing a timing
Use this as a decision guide:
- Need to change the incoming row or reject it before it is stored? Use
BEFORE. - Need to react to a change that has been stored, such as writing an audit row or updating a summary table? Use
AFTER. - Need to make a view writable? Use
INSTEAD OF.
The same table can have both. A common pattern is a BEFORE trigger that normalizes data and an AFTER trigger that records it.
Edge cases
- Exceptions abort the statement. An exception in either timing rolls back the whole statement, including rows already processed.
- Visibility. A
BEFOREtrigger sees the table as it was before the current row changed. AnAFTERtrigger sees the changed table, including rows touched by the same statement. - Cost.
BEFOREtriggers run immediately for each row.AFTERrow triggers must be queued until the statement ends, which uses memory on statements that touch millions of rows. - Deferral. Only constraint triggers, covered later, can be postponed to the end of the transaction. Ordinary
AFTERtriggers still run at the end of the statement.
Exercise
A BEFORE UPDATE row trigger on accounts always ends with RETURN NULL. A user runs UPDATE accounts SET balance = 10 WHERE id = 1. What happens to the row, and what does psql report?
Show answer
The update is skipped for that row. The row keeps its old values, and psql reports UPDATE 0, because returning NULL from a BEFORE row trigger cancels the operation for that row without raising an error.
Exercise
You want to record in an audit table the final stored value of a column that a different BEFORE trigger may adjust. Should the audit trigger be BEFORE or AFTER, and why?
Show answer
AFTER. An AFTER trigger runs once the row is stored, so NEW holds the final values including adjustments made by BEFORE triggers. A BEFORE audit trigger might log a value that is changed later.