Sub topic 1
What a trigger is and when to use one
Prerequisites
This chapter assumes you already know:
- Basic SQL:
SELECT,INSERT,UPDATE,DELETE, andCREATE TABLE. - How to run statements in
psqlor another PostgreSQL client. - What a transaction is: a group of statements that commit or roll back together.
- Helpful but not required: simple PL/pgSQL syntax such as
DECLARE,BEGIN,IF, andRAISE.
You do not need to write a trigger yet. This chapter builds the working model. Later chapters cover the syntax in detail.
What a trigger is
A trigger is a rule stored in the database that says: when a certain event happens on a table, call a certain function automatically. The events are INSERT, UPDATE, DELETE, and TRUNCATE. The function is called a trigger function. PostgreSQL runs it for you, inside the same transaction as the statement that caused it.
Every trigger has two parts:
- A trigger function. It is written in a procedural language, most often PL/pgSQL, and it is declared to return the special type
trigger. - A
CREATE TRIGGERcommand. It names the table, the event, the timing, and the function to call.
Keeping the two parts separate means one function can be attached to many tables.
Here is a small example. It keeps an updated_at column current whenever a row in accounts changes.
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();After this, any UPDATE accounts ... stamps the changed rows with the current time. The application does not have to remember to set the column. It cannot forget, and it cannot skip the step by accident.
How a trigger fits into a statement
The diagram shows what happens when a client runs an UPDATE on a table that has a BEFORE UPDATE row trigger and an AFTER UPDATE row trigger.
Three points follow from this picture:
- The trigger runs in the same session and the same transaction as the statement. If the transaction rolls back, everything the trigger did rolls back too.
- A
BEFOREtrigger runs before the row is written, so it can change the row or stop the statement. AnAFTERtrigger sees the finished change. - A trigger that raises an error aborts the whole statement.
Later chapters explain timing and granularity (per row or per statement) properly. For now, treat them as the two main choices you make when you define a trigger.
How a trigger differs from related tools
Triggers overlap with other ways of enforcing behavior. Picking the right one matters.
| Tool | Runs when | Best for | Limits |
|---|---|---|---|
| Constraint (`NOT NULL`, `CHECK`, `UNIQUE`, `FOREIGN KEY`) | On every write to the table | Declarative rules about a row or key | Cannot look at other tables (`CHECK`) or change data |
| Column `DEFAULT` | On `INSERT` when a column is omitted | Simple initial values | Does not apply on `UPDATE` |
| Trigger | On a chosen event, with a function | Logic that must change data, write elsewhere, or reject based on custom code | Hidden from the calling code, adds cost to every write |
| Rule (`CREATE RULE`) | The query is rewritten before it runs | Rare; view rewriting internals | Easy to misuse; triggers are usually clearer |
| Application code | Whenever the application runs it | Business logic, calls to outside systems | Bypassed by any other client that writes to the table |
The key difference between a trigger and application code is where the logic lives. Application code protects only the paths that go through the application. A trigger protects the table itself, whether the write came from the web app, a migration script, a data fix in psql, or a batch job.
The key difference between a trigger and a constraint is power and cost. A constraint is declarative and the planner understands it. A trigger is arbitrary code. It can do much more, but PostgreSQL cannot reason about it, and it is easier to get wrong.
When to use a trigger
Triggers are a good fit when the behavior must hold for every writer and cannot be expressed as a constraint. Common jobs:
- Maintaining derived columns such as
updated_at. - Writing an audit trail of who changed what.
- Enforcing a rule that needs custom logic or reads another table.
- Making a view writable (
INSTEAD OFtriggers). - Keeping a summary table in step with a detail table.
Each of these is covered by its own chapter later in the tutorial.
When not to use a trigger
Prefer something simpler when one of these applies:
- A constraint can express the rule. Use
CHECK,NOT NULL,UNIQUE, or a foreign key. They are faster and clearer. - A default or generated column can do the job. A
DEFAULT now()covers initial timestamps. A generated column covers values computed from the same row. - The logic calls an outside system, such as sending an email or an HTTP request. A trigger runs inside the transaction. A slow or failing call holds locks and can roll back the write. Write a row to a queue table instead and let a separate worker process it.
- The logic is a core business workflow with many steps. Hiding it in triggers makes it hard to find and test. A visible function or application code is easier to follow.
- The table takes very heavy bulk loads. A row-level trigger adds a function call per row.
Seeing triggers in the database
You can list the user-defined triggers on a table through the pg_trigger catalog. Internal triggers, such as those that implement foreign keys, are marked tgisinternal.
SELECT tgname, tgenabled
FROM pg_trigger
WHERE tgrelid = 'accounts'::regclass
AND NOT tgisinternal;In psql, the command \d accounts also lists the triggers at the bottom of its output.
Common first mistakes
- Forgetting the return statement. A trigger function must return a value, and in a
BEFORErow trigger the returned row is what gets written. The details come in the chapter on return values. - Assuming a trigger runs outside the transaction. It does not. An error in a trigger undoes the user's statement.
- Expecting a trigger on
TRUNCATEto see rows.TRUNCATEtriggers are statement-level only, so there are no per-row values. - Using a trigger where a constraint is enough. This adds cost and hides the rule.
Exercise
A team wants every write to the orders table to be rejected when quantity is not positive, whether the write comes from the web app, a nightly import script, or a DBA in psql. Which tool fits best, and why would application-level validation alone not be enough?
Show answer
A CHECK (quantity > 0) constraint fits best, because the rule looks only at the row itself and constraints are declarative and cheap. A trigger would also work but adds cost for no gain. Application validation alone is not enough because the import script and the DBA bypass the application, so only a rule stored in the database protects every writer.
Exercise
You need to send a welcome email whenever a row is inserted into accounts. Why is a trigger that calls the email service directly a poor design, and what is a better one?
Show answer
The trigger runs inside the inserting transaction. A slow or failing email call would hold locks, delay the insert, or roll it back. Also, if the transaction rolls back after the email is sent, the email cannot be unsent. A better design is a trigger that inserts a row into an outbox table, with a separate worker that reads the table and sends the emails after the transaction commits.