# Topic 50: Triggers & Recursive CTEs
BEFORE/AFTER row triggers, audit trail generation, recursive hierarchical graphs, and infinite recursion guards.
1. Definition
Triggers automatically execute procedural logic when specific DML events occur. Recursive CTEs iteratively traverse graphs, organizational charts, and hierarchical relational trees.
2. Explain Like I'm 5
A Trigger is a tripwire: whenever someone opens a door, an alarm rings or a camera snaps a photo automatically. A Recursive CTE is climbing a family tree from child to parent to grandparent until you reach the root.
3. Animation & Visual Simulation
Interactive Engine TraceTriggers & Recursive CTEs Visual Simulator
WITH RECURSIVE cnt(x) AS (
SELECT 1
UNION ALL
SELECT x + 1 FROM cnt WHERE x < 10
)
SELECT x FROM cnt;Active InputStep 1: Input & Parsing Stage
Initiating Triggers & Recursive CTEs
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Traversing an organizational chart of employees and managers to calculate corporate reporting chains.
| Level | Employee | Manager |
|---|---|---|
| 1 | CEO | NULL (Root) |
| 2 | VP Engineering | CEO |
| 3 | Staff Engineer | VP Engineering |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectWITH RECURSIVE org_tree AS ( -- 1. Anchor member (Root node): SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id IS NULL UNION ALL -- 2. Recursive member (Joins parent): SELECT e.id, e.name, e.manager_id, ot.depth + 1 FROM employees e JOIN org_tree ot ON e.manager_id = ot.id ) SELECT * FROM org_tree ORDER BY depth, id;
CREATE OR REPLACE FUNCTION log_user_update() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN INSERT INTO user_audit_log (user_id, old_email, new_email, changed_at) VALUES (OLD.id, OLD.email, NEW.email, NOW()); RETURN NEW; END; $$; CREATE TRIGGER trg_user_audit AFTER UPDATE OF email ON users FOR EACH ROW EXECUTE FUNCTION log_user_update();
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Anchor & Recursive Structure | A recursive CTE strictly consists of an Anchor query, UNION ALL, and a Recursive query referencing the CTE name. |
| Infinite Recursion Guard | Graph cycles (e.g. A reports to B and B reports to A) cause infinite loops unless guarded by depth limits or array cycle tracking. |
| OLD and NEW in Triggers | In row-level triggers, OLD represents row state before modification; NEW represents proposed modified state. |
| BEFORE vs AFTER trigger semantics | BEFORE triggers can modify the incoming NEW tuple before write; AFTER triggers run post-write for auditing. |
| Recursive CTE termination guard | Recursive CTEs require an empty set termination condition to prevent infinite loops and stack overflows. |
7. Deep Dive: Cycle Detection in Graph Traversals
If your relational hierarchy contains cyclic loops (e.g. node 1 -> node 2 -> node 1), a naive recursive CTE runs forever until memory exhausts. In PostgreSQL, use an array path to detect cycles.
WITH RECURSIVE search_graph(id, link, path, cycle) AS ( SELECT g.id, g.link, ARRAY[g.id], false FROM graph g UNION ALL SELECT g.id, g.link, path || g.id, g.id = ANY(path) FROM graph g, search_graph sg WHERE g.id = sg.link AND NOT cycle ) SELECT * FROM search_graph WHERE NOT cycle;
8. Advantages & Disadvantages
Advantages
- •Solves graph and tree traversal natively in SQL without procedural application loops.
- •Triggers guarantee unbypassable audit logging.
Disadvantages & Trade-offs
- •Triggers execute hidden logic that can surprise developers and cause lock contention.
9. Common Interview Questions
Q1.What is the architectural difference between BEFORE and AFTER triggers in relational engines?
1. BEFORE Triggers execute before the tuple is written to the 8 KB disk page. They can inspect and mutate the special NEW record (e.g. sanitizing input, setting default timestamps, hashing passwords) or cancel the operation by returning NULL. 2. AFTER Triggers execute after the tuple is written and indexed. They cannot modify the NEW record; they are used for cascading operations, audit logging, and message queue notifications.
Q2.How does a Recursive Common Table Expression (CTE) execute step by step?
A Recursive CTE consists of: 1. Anchor Member: executes once to generate the base initial result set and places it in an intermediate working table. 2. Recursive Member: executes repeatedly, referencing the working table from the previous step and joining to base tables, replacing the working table with newly generated rows. 3. Termination: when the recursive step returns zero rows, the engine unions all intermediate sets and returns the final result.
WITH RECURSIVE org_tree AS ( -- Anchor member: CEO (top of tree) SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id IS NULL UNION ALL -- Recursive member: direct reports SELECT e.id, e.name, e.manager_id, o.depth + 1 FROM employees e JOIN org_tree o ON e.manager_id = o.id ) SELECT * FROM org_tree ORDER BY depth, id;
Q3.How do you detect and prevent infinite loops in Recursive CTEs caused by cyclic graphs?
If employee A reports to B and B reports to A (a cyclic graph), a recursive CTE will loop infinitely until memory or integer overflow occurs. In PostgreSQL 14+, you use the CYCLE clause: CYCLE id SET is_cycle USING path; In older versions, you track an array of visited IDs: WHERE e.id != ALL(visited_array) and append array_append(visited_array, e.id).
Q4.What is the performance difference between ROW-level and STATEMENT-level triggers?
A Statement-Level Trigger executes exactly ONCE per SQL statement, regardless of whether the statement touches 1 row or 1,000,000 rows. A Row-Level Trigger (FOR EACH ROW) executes once for EVERY SINGLE ROW modified. Firing a row-level trigger 1 million times incurs massive CPU context-switching overhead and can degrade an insert from 2 seconds to 45 seconds.
Q5.Why are database triggers often considered an architectural antipattern in modern microservices?
1. Hidden side effects: Developers debugging application code cannot see triggers executing behind the scenes in the database. 2. Performance bottlenecks: Heavy trigger logic blocks the client transaction, increasing lock durations and connection wait times. 3. Horizontal scaling: Database CPU is expensive; business events are better handled asynchronously using Change Data Capture (CDC / Debezium) and event streaming (Kafka/RabbitMQ).
10. Interview-Ready Answer
“Recursive CTEs iteratively traverse graphs and hierarchies by combining an anchor query with a recursive member until termination. Database triggers enforce unbypassable audit logs and constraints by capturing row-level OLD and NEW transitions.”
11. Quick Test
What is the purpose of the Anchor Member in a Recursive CTE?