Skip to content
Back to 50 Concepts
Topic 50 of 50architectureExpert

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Triggers & Recursive CTEs Visual Simulator

Step 1 of 3
SQL>WITH RECURSIVE cnt(x) AS ( SELECT 1 UNION ALL SELECT x + 1 FROM cnt WHERE x < 10 ) SELECT x FROM cnt;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Triggers & Recursive CTEs
SQL Input

Initiating Triggers & Recursive CTEs

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Domino Chain: The anchor member tips the first domino; the recursive member causes each subsequent domino to fall until none remain.

4. Real-World Example

Traversing an organizational chart of employees and managers to calculate corporate reporting chains.

Organization Tree
LevelEmployeeManager
1CEONULL (Root)
2VP EngineeringCEO
3Staff EngineerVP Engineering
Relational walkthrough: A Recursive CTE starts with the CEO anchor member and iteratively joins child employees.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Recursive CTE traversing hierarchy
WITH 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;
Iterates until the join produces no new rows.
Step 2: Automated Audit Trigger with BEFORE/AFTER
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

RuleBehavioral Explanation
Anchor & Recursive StructureA recursive CTE strictly consists of an Anchor query, UNION ALL, and a Recursive query referencing the CTE name.
Infinite Recursion GuardGraph 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 TriggersIn row-level triggers, OLD represents row state before modification; NEW represents proposed modified state.
BEFORE vs AFTER trigger semanticsBEFORE triggers can modify the incoming NEW tuple before write; AFTER triggers run post-write for auditing.
Recursive CTE termination guardRecursive 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;
Caution: Always set a safety limit (e.g. WHERE depth < 50) when querying recursive trees.

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

Scenario Question:

What is the purpose of the Anchor Member in a Recursive CTE?

Select your answer: