Sub topic 1
What a Trigger Is and When to Use One
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE, and CREATE TABLE), can connect to PostgreSQL with psql or another client, and understand that a transaction groups statements so they succeed or fail together. Familiarity with simple PL/pgSQL (DECLARE, BEGIN, IF, RETURN) helps but is not required.
What a trigger is and when to use one
A trigger is a rule that tells PostgreSQL to run a function automatically when a table changes. The change can be an INSERT, UPDATE, DELETE, or TRUNCATE. A constraint only checks data, and a rule rewrites a query. A trigger runs code, so it can change or reject rows. Use one when the database must enforce behavior no matter which application writes the data, such as keeping an updated_at column current or writing an audit log.
Writing a trigger function
A trigger function is a PL/pgSQL function that returns the special type trigger. Inside it, NEW holds the incoming row and OLD holds the previous row. The following function sets updated_at on every update.
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;
$$;Attaching a function with CREATE TRIGGER
CREATE TRIGGER binds a function to a table and an event. Each trigger names its timing, its granularity, and its events.
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();BEFORE, AFTER, and INSTEAD OF
- BEFORE runs before the row is written. It can modify
NEWor raise an error to stop the write. - AFTER runs once the row change is queued. Use it for side effects such as logging, because its return value is ignored.
- INSTEAD OF runs in place of the write. It applies only to views.
FOR EACH ROW vs FOR EACH STATEMENT
A row-level trigger fires once for each affected row. A statement-level trigger fires once per SQL statement, even if that statement changes zero rows or a million rows. Row-level triggers see OLD and NEW. Statement-level triggers do not.
Exercise
Should a timestamp-maintenance trigger use BEFORE or AFTER timing, and why?
Show answer
Use BEFORE. A BEFORE trigger can change NEW.updated_at before the row is written. An AFTER trigger cannot change the stored row, because its return value is ignored.