Sub topic 17
Performance costs and alternatives to triggers
This chapter assumes you can write a PL/pgSQL trigger function, attach it with CREATE TRIGGER, and tell row-level from statement-level triggers. It uses the accounts and accounts_audit tables from earlier chapters. The goal is to find out what a trigger costs, reduce that cost, and decide when a different tool fits better.
Where the cost comes from
A trigger is cheap for one row and expensive for a million. The costs add up per row:
- Function call overhead. A row-level trigger calls its function once for every affected row. PL/pgSQL has to set up the call and bind
NEWandOLDeach time. - Hidden statements. An audit trigger runs an
INSERTper row. Each one writes WAL (the write-ahead log) and may update indexes on the audit table. - Queued events. Postgres stores each pending
AFTERrow event in memory until the statement ends. If the trigger is deferred, it stores the event until commit. A bulk statement with manyAFTERrow triggers can use a lot of memory. - Contention. Many sessions writing to one shared audit or counter table can block each other. A trigger that does
UPDATE totals SET n = n + 1serializes every writer on that one row. - Invisible work. The statement the application sent looks simple, so slow writes are hard to explain unless you know the triggers exist.
Foreign keys work the same way. Postgres implements them as internal AFTER triggers, which is why they show up in the timing output below.
Measuring a trigger
EXPLAIN ANALYZE reports time spent in each trigger. It really runs the statement, so wrap it in a transaction and roll back.
BEGIN;
EXPLAIN (ANALYZE)
UPDATE accounts SET balance = balance + 1;
ROLLBACK;The end of the plan lists one line per trigger:
Trigger accounts_set_updated_at: time=412.350 calls=100000
Trigger accounts_audit_trg: time=2890.114 calls=100000
Execution Time: 4120.882 msThese numbers are illustrative. Compare your own trigger time to the total execution time. If calls equals the number of rows, you have a per-row cost. Reducing the calls is usually the first fix.
Cutting the work
Apply these in order. Each one removes calls instead of making each call faster.
- Skip no-op updates.
WHEN (OLD.* IS DISTINCT FROM NEW.*)stops Postgres from calling the function when nothing changed. - Limit columns.
UPDATE OF balancefires only when theUPDATEstatement names that column in itsSETlist. - Use
BEFOREfor changes to the row itself. SettingNEW.updated_atin aBEFOREtrigger needs no second write. AnAFTERtrigger that runs its ownUPDATEon the same row writes it twice. - Go set-based. A statement-level trigger with transition tables runs once per statement, however many rows it touches.
Here is a row-level audit rewritten as a statement-level trigger. Transition tables allow only one event per trigger, so you need one trigger for each of INSERT, UPDATE, and DELETE. This one handles UPDATE.
CREATE FUNCTION audit_accounts_bulk_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO accounts_audit (account_id, operation, old_row, new_row)
SELECT n.id, 'UPDATE', to_jsonb(o), to_jsonb(n)
FROM old_rows o
JOIN new_rows n ON n.id = o.id;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_audit_bulk_upd
AFTER UPDATE ON accounts
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT
EXECUTE FUNCTION audit_accounts_bulk_update();The function is called once. The audit rows go in through a single INSERT ... SELECT, which Postgres plans as a set operation. Joining on id is safe here because id is the primary key.
Turning triggers off for bulk loads
For a one-off data load, you can disable a trigger and re-enable it afterward. You must then do its work another way, for example by back-filling the audit rows or updated_at values yourself.
ALTER TABLE accounts DISABLE TRIGGER accounts_audit_trg;
-- run the bulk load here
ALTER TABLE accounts ENABLE TRIGGER accounts_audit_trg;ALTER TABLE ... DISABLE TRIGGER takes a lock on the table and affects every session, not just yours. Setting session_replication_role = replica as a superuser skips ordinary triggers for one session. It also skips the logic they enforce, so use it only when you know that is safe.
Alternatives to triggers
A trigger is the most flexible option and often the most expensive one. Use a declarative feature when one fits, because the planner and the catalog understand it.
| Need | Alternative | Why it is better |
|---|---|---|
| Reject negative balances | `CHECK` constraint | Evaluated inline, visible in `\d`, and no function call |
| Default value at insert | `DEFAULT` expression | No code to maintain |
| Value computed from other columns | Generated column | Always consistent, and the planner can use it |
| Referential rules | `FOREIGN KEY` | Handles locking and cascades correctly |
| Uniqueness or no overlap | `UNIQUE` or `EXCLUDE` constraint | Uses an index, so it is safe under concurrency |
| Show a different shape of data | View or materialized view | No write-path cost |
| Push changes to other systems | Logical decoding or `LISTEN`/`NOTIFY` | Work moves out of the writing transaction |
The first row has a simple form:
ALTER TABLE accounts
ADD CONSTRAINT balance_non_negative CHECK (balance >= 0);This does the job of forbid_negative_balance() without PL/pgSQL. A constraint can only look at the row being written. If the rule needs another table, or a custom error message built from several values, a trigger is still the right tool.
Generated columns cannot replace updated_at. A generated expression must be immutable, and now() is not. Keep the BEFORE UPDATE trigger for that, with a WHEN clause.
For heavy side effects such as sending email or calling an API, do not put the work in the trigger. The call runs inside the transaction and holds locks while it waits. Instead, have the trigger insert a row into an outbox table, and let a separate worker process the queue.
Common mistakes
- Using
AFTERtriggers to modify the same row. UseBEFOREand editNEW. - Forgetting that
UPDATE OF colfires when the column appears inSET, even if the value does not change. Pair it withWHENif no-op writes matter. - Auditing every column of a wide table as
jsonb. The audit table can grow faster than the data itself. - Adding a trigger that updates a shared counter row. Compute the aggregate on read, or batch the updates.
Exercise
An UPDATE accounts SET email = lower(email) touches 200,000 rows. EXPLAIN (ANALYZE) shows Trigger accounts_audit_trg: calls=200000 and most of the runtime. Name two changes that reduce this cost, and say what each one changes.
Show answer
First, replace the row-level audit trigger with a statement-level AFTER UPDATE trigger that uses REFERENCING OLD TABLE and NEW TABLE. The function then runs once and writes all audit rows with one INSERT ... SELECT. Second, add WHEN (OLD.* IS DISTINCT FROM NEW.*) to the existing row-level trigger. Rows whose email is already lowercase then never call the function. A third option is to disable the trigger during a one-off load, but that skips auditing for those rows.
Exercise
Why can a generated column not replace the BEFORE UPDATE trigger that sets updated_at := now()?
Show answer
A generated column expression must be immutable, meaning it depends only on the row's own columns. now() returns a different value over time, so Postgres rejects it. The trigger is still needed.