Sub topic 4
BEFORE, AFTER, and INSTEAD OF Triggers
Assume you know basic INSERT, UPDATE, DELETE, transactions, and simple PL/pgSQL. This chapter focuses on trigger timing: when PostgreSQL runs a trigger relative to the data change.
A trigger is attached to a table or view and runs a trigger function when a database event occurs. The timing determines whether the function can change the row, observe the completed change, or replace the operation.
The three timing choices
| Timing | Runs | Typical use |
|---|---|---|
| `BEFORE` | Before PostgreSQL writes the row | Set derived values or reject data |
| `AFTER` | After PostgreSQL writes the row | Record an audit event or notify another process |
| `INSTEAD OF` | Instead of an operation on a view | Translate view writes into base-table writes |
A BEFORE trigger can modify NEW. For example, it can calculate a normalized value or set an update timestamp. Returning NEW tells PostgreSQL to continue with the modified row. Returning NULL skips the operation for that row.
An AFTER trigger sees the result after the row has been written. Its return value is ignored, so trigger functions commonly return NULL. The trigger still runs inside the same transaction. If the statement later fails or the transaction rolls back, work performed by the AFTER trigger rolls back too.
An INSTEAD OF trigger is available on views. It replaces the requested operation. The function must perform the corresponding work on one or more base tables. Returning a non-null row reports that the view operation was handled.
A `BEFORE` trigger can change `NEW`
This complete example keeps updated_at current whenever an account row changes:
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
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();Because the trigger is row-level, PostgreSQL calls the function once for every updated row. A BEFORE trigger can also raise an exception to reject the row.
An `AFTER` trigger observes the completed change
Use AFTER when the trigger should not alter the row being written. An audit trigger can inspect OLD and NEW:
CREATE FUNCTION audit_account_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'Account % changed from % to %',
NEW.id, OLD.email, NEW.email;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_audit_update
AFTER UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_account_update();For INSERT, NEW is available but OLD is not. For DELETE, OLD is available but NEW is not.
`INSTEAD OF` makes a view writable
A view normally does not store independent rows. An INSTEAD OF trigger can route an insert into its underlying table:
CREATE VIEW account_emails AS
SELECT id, email FROM accounts;
CREATE FUNCTION insert_account_email() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO accounts (email)
VALUES (NEW.email)
RETURNING id, email, updated_at INTO NEW.id, NEW.email, NEW.updated_at;
RETURN NEW;
END;
$$;
CREATE TRIGGER account_emails_insert
INSTEAD OF INSERT ON account_emails
FOR EACH ROW
EXECUTE FUNCTION insert_account_email();The trigger returns the row that PostgreSQL should report as inserted into the view.
Exercise
What happens if a BEFORE row-level trigger returns NULL for one updated row?
Show answer
PostgreSQL skips that row's update, while other rows in the same statement can continue.