Sub topic 16
Recursion, Cascades, and Common Pitfalls
This chapter assumes that you know basic SQL, transactions, and the difference between BEFORE and AFTER triggers. It also assumes that you can read simple PL/pgSQL functions.
A trigger can run SQL that changes another table or even the table that caused the trigger. That power creates two common risks:
- Recursion: a trigger causes its own event again.
- Cascading work: one data change causes triggers on several related tables to run.
How recursion happens
A BEFORE trigger can change NEW directly. This does not issue another UPDATE, so it does not recursively fire an update trigger.
CREATE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;An AFTER trigger cannot change the stored row by changing NEW. A careless implementation might issue another update instead:
CREATE FUNCTION bad_set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
UPDATE accounts
SET updated_at = now()
WHERE id = NEW.id;
RETURN NULL;
END;
$$;If this function is attached to AFTER UPDATE ON accounts, its UPDATE fires the same trigger again. The process can continue until PostgreSQL reaches a stack-depth limit or the transaction fails.
Use a BEFORE trigger for values that belong to the row being written. If a second statement is necessary, make the operation idempotent and add a clear guard condition. For example, update only when the target value is actually different.
The function pg_trigger_depth() reports the current trigger nesting depth. It can help with diagnosis, but it is usually a poor business rule. A depth check can hide legitimate work and make behavior depend on how the operation was reached.
Cascades across related tables
Foreign keys can perform cascading actions such as ON DELETE CASCADE or ON UPDATE CASCADE. These actions change rows in other tables, and triggers on those tables can run.
flowchart TD
A[Delete customer] --> B[Foreign key cascade]
B --> C[Delete customer orders]
C --> D[Order DELETE triggers run]
A --> E[Customer DELETE triggers run]A single statement can therefore produce more trigger calls than its directly affected rows suggest. Audit logs should record the actual table and operation. Do not assume that every change came from a direct application statement.
Common pitfalls
| Pitfall | Result | Safer approach |
|---|---|---|
| Updating the same table from its update trigger | Recursion or repeated work | Change `NEW` in a `BEFORE` trigger |
| Assuming one SQL statement means one row change | Missing cascaded effects | Test foreign-key actions and related triggers |
| Writing audit rows to a table with the same audit trigger | A second recursion chain | Keep audit tables separate and inspect their triggers |
| Using a broad trigger for every update | Unnecessary calls and slower writes | Use `UPDATE OF column` and `WHEN` where appropriate |
| Disabling triggers during normal application work | Constraint or audit gaps | Disable only in controlled maintenance operations |
A safer design checklist
- Keep trigger functions small and predictable.
- Avoid hidden writes to the triggering table.
- Prefer constraints for simple column rules.
- Test direct changes and foreign-key cascades in one transaction.
- Include a transaction rollback test for rejected changes.
- Inspect trigger depth and server logs when debugging unexpected calls.
Exercise
An AFTER UPDATE trigger runs UPDATE accounts SET updated_at = now() for the same row. What is the main danger, and what design should replace it?
Show answer
The UPDATE fires the trigger again and can recurse until the transaction fails. Replace it with a BEFORE UPDATE trigger that assigns NEW.updated_at and returns NEW.