Sub topic 16
Recursion, cascades, and common pitfalls
This chapter assumes you can write a PL/pgSQL trigger function, attach it with CREATE TRIGGER, and use NEW, OLD, and TG_OP. It covers the ways triggers cause trouble when they act on each other or on the table that fired them. Most of these problems appear only once a second trigger or a bulk statement is involved.
How triggers chain
A trigger function runs ordinary SQL. If that SQL changes a table, any triggers on that table fire as well. PostgreSQL does not stop this for you. It does not detect loops, and the only protection is the server's stack depth limit, which ends the loop with an error.
Chains come in two shapes:
- Cascade: a trigger on table A writes to table B, and B has its own trigger that writes to table C. This is legitimate when the chain ends.
- Recursion: a trigger writes to the table that fired it, directly or through other tables, and the same trigger fires again.
Recursion in an AFTER trigger
Suppose you want to keep a last_balance_change column current. Putting the update in an AFTER trigger causes infinite recursion:
ALTER TABLE accounts ADD COLUMN last_balance_change timestamptz;
CREATE FUNCTION touch_balance_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
UPDATE accounts
SET last_balance_change = now()
WHERE id = NEW.id;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_touch
AFTER UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION touch_balance_change();Every UPDATE on accounts runs the function, which runs another UPDATE, which runs the function again. The statement fails with stack depth limit exceeded, and the whole change rolls back.
Fix 1: use a BEFORE trigger and change NEW
If the goal is to change the row being written, do it in a BEFORE row trigger. Assigning to NEW and returning it needs no second UPDATE, so nothing re-fires:
DROP TRIGGER accounts_touch ON accounts;
CREATE OR REPLACE FUNCTION touch_balance_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.last_balance_change := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_touch
BEFORE UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION touch_balance_change();This is the right fix whenever the trigger only edits the row that fired it.
Fix 2: narrow the firing condition
When the trigger must write to the same table, make the second pass a no-op with UPDATE OF or WHEN. The nested update below touches only last_balance_change, so a trigger declared AFTER UPDATE OF balance does not fire for it. A WHEN (OLD.balance IS DISTINCT FROM NEW.balance) condition works the same way.
Fix 3: check the nesting depth
pg_trigger_depth() returns how many triggers are currently running. A guard at the top of the function stops re-entry:
IF pg_trigger_depth() > 1 THEN
RETURN NULL;
END IF;Use this as a last resort. It also silences legitimate cascades from other triggers, because the depth counts every trigger in the chain, not only this one.
Cascades across tables
A cascade is fine when it has a clear end. It becomes a loop when two tables write to each other. If a trigger on orders updates customers and a trigger on customers updates orders, each update re-fires the other. Draw the write graph of your triggers on paper. If the graph has a cycle, break it with a WHEN condition that stops once the values already match.
Foreign key actions (ON DELETE CASCADE, ON UPDATE SET NULL) are implemented internally with triggers. Their changes to the child table fire your user triggers on that table. A delete on a parent can therefore run audit triggers on thousands of child rows.
Common pitfalls
Returning the wrong value
In a BEFORE row trigger, RETURN NULL silently skips the operation for that row. No error appears and the statement reports fewer rows affected. A forgotten RETURN NEW is a frequent cause of "my insert does nothing". In a BEFORE DELETE trigger, return OLD, because NEW is not set for deletes. Returning NEW there is the same as returning NULL and cancels the delete.
Using NEW or OLD where they do not exist
OLD is not available in INSERT triggers, and NEW is not available in DELETE triggers. In PostgreSQL 11 and later, referencing the missing record raises an error, so a single function that handles several events must branch on TG_OP first. Statement-level triggers have neither record.
Doing row work in a statement trigger, or the reverse
A row trigger on a statement that touches 100,000 rows runs 100,000 times. If the work can be done once per statement, use FOR EACH STATEMENT with a transition table.
Assuming a fixed firing order
Triggers of the same timing and level fire in alphabetical order by name. Renaming a trigger can change behavior. Name triggers with a numeric prefix, such as 10_validate and 20_audit, if order matters.
Side effects that cannot be rolled back
Triggers run inside the caller's transaction, so table writes roll back with it. Calls that leave the database do not. A function that sends a network request or writes a file has already acted when the transaction aborts. Sequence values also stay consumed. Queue the work in a table and let a separate worker process it after commit.
Hidden behavior
Triggers do not appear in the application's code, so a simple UPDATE may do far more than its text suggests. Keep trigger logic small and document it. Use pg_trigger_depth() and RAISE NOTICE while debugging, and list triggers with pg_trigger as shown in the management chapter.
Bulk loads and replication
COPY fires row triggers, which makes loads slow. Disabling triggers with ALTER TABLE ... DISABLE TRIGGER for a load skips your rules, so re-check the data afterward. Triggers also do not fire on logical replication subscribers unless you set them to ENABLE ALWAYS or ENABLE REPLICA.
Summary table
| Symptom | Likely cause | Fix |
|---|---|---|
| `stack depth limit exceeded` | Trigger updates its own table | BEFORE trigger on `NEW`, or `UPDATE OF`/`WHEN` |
| Insert or update affects 0 rows | BEFORE trigger returned `NULL` | Return `NEW` (or `OLD` for deletes) |
| Delete does nothing | BEFORE DELETE returned `NEW` | Return `OLD` |
| Error on `OLD` or `NEW` | Wrong event for that record | Branch on `TG_OP` |
| Rules run in a surprising order | Alphabetical firing order | Rename with ordered prefixes |
Exercise
A trigger declared AFTER UPDATE ON orders FOR EACH ROW runs UPDATE orders SET modified = now() WHERE id = NEW.id and fails with "stack depth limit exceeded". Give two different ways to fix it.
Show answer
First, change it to a BEFORE UPDATE row trigger that sets NEW.modified := now() and returns NEW, so no second UPDATE is issued. Second, keep the nested UPDATE but restrict the trigger so the nested update does not fire it again, for example with AFTER UPDATE OF status (so an update that touches only modified does not fire it) or a WHEN condition that compares the relevant old and new values.
Exercise
A BEFORE DELETE row trigger validates the row and ends with RETURN NEW. Deletes now report "DELETE 0". Why, and what is the fix?
Show answer
NEW is not assigned in DELETE triggers, so RETURN NEW returns NULL, and a NULL return from a BEFORE row trigger skips the operation for that row. Return OLD instead.