Sub topic 3
Attaching a Function with `CREATE TRIGGER`
Assume you know basic SQL, PostgreSQL transactions, and simple PL/pgSQL syntax. A trigger function contains the logic. A trigger connects that function to an event on a table or view.
Create the function first. It must return the special trigger type:
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;
$$;The NEW record contains the row after the proposed change. This function changes its timestamp and returns it. The trigger can then call the function:
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();CREATE TRIGGER describes when PostgreSQL should invoke the function.
| Part | Meaning |
|---|---|
| `accounts_set_updated_at` | The trigger's name on this table |
| `BEFORE UPDATE` | Run before PostgreSQL writes an updated row |
| `ON accounts` | Attach the trigger to the `accounts` table |
| `FOR EACH ROW` | Invoke it once for every affected row |
| `EXECUTE FUNCTION ...()` | Call the trigger function |
An UPDATE that affects 100 rows invokes a row-level trigger 100 times. The trigger runs inside the same transaction as the statement. If the function raises an exception, the statement fails and its changes are rolled back.
Selecting the trigger event
A trigger can respond to INSERT, UPDATE, DELETE, or TRUNCATE. You can combine compatible events:
CREATE TRIGGER accounts_audit_changes
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();The referenced function must handle every event listed. It can inspect TG_OP, whose value is the event name, such as 'INSERT' or 'DELETE'.
You can limit an update trigger to updates that name a particular column:
CREATE TRIGGER accounts_balance_check
BEFORE UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION forbid_negative_balance();This fires when balance appears in the SET list. It does not necessarily mean that the value changed. Use a WHEN condition when the trigger should run only for a particular row state:
CREATE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION set_updated_at();The WHEN condition is evaluated for each row. It can prevent unnecessary function calls, but it cannot contain a subquery.
> callout note > A trigger name only needs to be unique among triggers on the same table. Use descriptive names that identify the table, event, and purpose.
Choosing a trigger definition
Choose the timing and granularity deliberately:
- Use
BEFOREwhen you need to modifyNEWor reject a row. - Use
AFTERwhen the row must already be stored, such as for audit logging. - Use
INSTEAD OFfor triggers on views. - Use
FOR EACH ROWwhen logic depends on individual rows. - Use
FOR EACH STATEMENTwhen one call should handle the whole SQL statement.
Exercise
What trigger definition runs set_updated_at before every changed row in accounts?
Show answer
CREATE TRIGGER accounts_set_updated_at BEFORE UPDATE ON accounts FOR EACH ROW EXECUTE FUNCTION set_updated_at();