Sub topic 3
Attaching a function with CREATE TRIGGER
This chapter assumes you can write basic SQL and have a PL/pgSQL trigger function that returns trigger, as in the previous chapter. A trigger function does nothing on its own. CREATE TRIGGER binds it to a table (or view) and to the events that should run it.
The anatomy of a trigger definition
A trigger definition answers five questions: what to call it, when it fires relative to the event, which events fire it, which table it watches, and which function it runs.
CREATE [ OR REPLACE ] TRIGGER name
{ BEFORE | AFTER | INSTEAD OF } event [ OR event ... ]
ON table_name
[ FOR [ EACH ] { ROW | STATEMENT } ]
[ WHEN ( condition ) ]
EXECUTE FUNCTION function_name ( [ arguments ] );Here event is one of INSERT, UPDATE [ OF column, ... ], DELETE, or TRUNCATE.
| Clause | Purpose | Default or rule |
|---|---|---|
| `name` | Identifies the trigger | Must be unique per table. It cannot be schema-qualified. |
| `BEFORE`, `AFTER`, `INSTEAD OF` | When the function runs | Required. Later chapters cover the differences. |
| `event` list | Which commands fire it | Join events with `OR`. |
| `ON table_name` | The table or view being watched | The trigger lives in that table's schema. |
| `FOR EACH ...` | Once per row or once per statement | `STATEMENT` if omitted. |
| `WHEN (condition)` | Skips the call when false | Optional. It cannot contain subqueries. |
| `EXECUTE FUNCTION` | The function to call | It must return `trigger` and declare no parameters. |
The default granularity is a common trap. If you forget FOR EACH ROW, you get a statement-level trigger, where NEW and OLD are not available.
A complete, runnable example
Create the function first. Then create the trigger that uses it.
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();Test it:
INSERT INTO accounts (email) VALUES ('[email protected]');
UPDATE accounts SET balance = 10 WHERE email = '[email protected]';
SELECT email, balance, updated_at > created_probe AS touched
FROM (SELECT *, now() - interval '1 second' AS created_probe FROM accounts) s;A simpler check is to run SELECT updated_at FROM accounts; before and after the update, in separate transactions. now() returns the transaction start time, so two statements in one transaction show the same value.
Passing arguments to the function
The EXECUTE FUNCTION clause accepts literal arguments, written as string constants or plain names. The function itself still declares no parameters. It reads the values from TG_ARGV, a zero-based text array, and TG_NARGS gives the count.
CREATE FUNCTION announce() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'label=%, table=%, op=%', TG_ARGV[0], TG_TABLE_NAME, TG_OP;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_announce
AFTER INSERT ON accounts
FOR EACH ROW
EXECUTE FUNCTION announce('new-account');All arguments arrive as text. Convert them yourself if you need numbers. Arguments are fixed when the trigger is created, so one function can serve several triggers that pass different values.
Reusing one function on several tables
The binding is many-to-many. One function can back triggers on many tables, as long as it only touches columns every table has.
CREATE TABLE projects (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TRIGGER projects_set_updated_at
BEFORE UPDATE ON projects
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();The trigger name projects_set_updated_at could even be accounts_set_updated_at. Names only need to be unique within one table. Many teams still prefix them with the table name to keep error messages readable.
Changing an existing trigger
If you run CREATE TRIGGER with a name already used on that table, PostgreSQL stops with trigger "accounts_set_updated_at" for relation "accounts" already exists. You have two options.
- Use
CREATE OR REPLACE TRIGGER(PostgreSQL 14 and later). It replaces the definition when a trigger of that name exists on the table and creates it otherwise. - Run
DROP TRIGGER IF EXISTS name ON table;and thenCREATE TRIGGER. This works on older versions.
For example, this adds a WHEN condition to the existing trigger without dropping it first:
CREATE OR REPLACE TRIGGER accounts_set_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION set_updated_at();Replacing the trigger does not change the function. To change the function body, use CREATE OR REPLACE FUNCTION. Existing triggers pick up the new body on their next firing.
Permissions and dependencies
- You need the
TRIGGERprivilege on the table, andEXECUTEprivilege on the trigger function. Table owners have the first one implicitly. - The function must exist when you run
CREATE TRIGGER. Create it first, in a schema on yoursearch_pathor with a schema-qualified name such asEXECUTE FUNCTION audit.set_updated_at(). - The trigger depends on its function.
DROP FUNCTION set_updated_at()fails while triggers use it, unless you addCASCADE, which also drops those triggers. - Dropping the table drops its triggers automatically.
Common errors
| Message | Cause |
|---|---|
| `function set_updated_at() does not exist` | The function was not created yet, is in another schema, or was created with parameters. |
| `function set_updated_at must return type trigger` | The function was declared with another return type, such as `void`. |
| `trigger functions cannot have declared arguments` | The function was declared with parameters. Remove them and read `TG_ARGV` instead. |
| `trigger "..." for relation "..." already exists` | Duplicate name on the same table. Use `OR REPLACE` or drop first. |
| `permission denied for table accounts` | The role lacks the `TRIGGER` privilege on the table. |
Exercise
You run CREATE TRIGGER stamp AFTER INSERT ON accounts EXECUTE FUNCTION announce('x'); and the function reads NEW.email. The statement is accepted. What happens when you insert a row, and what one-line change to the definition fixes it?
Show answer
The trigger is statement-level because FOR EACH ROW was omitted, so NEW is not assigned and the function fails when it reads NEW.email. Add FOR EACH ROW before EXECUTE FUNCTION to make it a row-level trigger.
Exercise
A trigger named audit_trg already exists on accounts and you want to add WHEN (OLD.balance IS DISTINCT FROM NEW.balance) to it on PostgreSQL 15. Which statement does this in one step, and what changes if you only change the function body instead?
Show answer
CREATE OR REPLACE TRIGGER audit_trg ... WHEN (...) EXECUTE FUNCTION ...; with the full definition repeated. Changing only the function body with CREATE OR REPLACE FUNCTION leaves the trigger definition, including its events and WHEN clause, untouched, and the trigger runs the new body on its next firing.