Recursive Query
ELI5 — The Vibe Check
A recursive query is SQL that calls itself, like a mirror reflecting a mirror. It's perfect for tree structures like org charts, comment threads, or category hierarchies. You give it a starting point and rules for finding the next level, and it keeps going until it runs out of matches.
Real Talk
A recursive query uses a recursive CTE (WITH RECURSIVE) to traverse hierarchical or graph-like data structures. It consists of an anchor member (base case) and a recursive member that references itself. PostgreSQL supports recursive CTEs for tree traversal, graph paths, and generating series. Cycle detection prevents infinite loops.
Show Me The Code
WITH RECURSIVE org_tree AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, t.depth + 1
FROM employees e
JOIN org_tree t ON e.manager_id = t.id
)
SELECT * FROM org_tree ORDER BY depth;
When You'll Hear This
"We use recursive queries to traverse the entire category tree." / "Recursive CTEs are the SQL way to handle parent-child relationships."
Related Terms
Common Table Expression
A CTE (WITH clause) lets you name a sub-query and use it later, like setting a variable in your SQL.
Graph Database
A graph database stores data as dots connected by lines, like a social network map.
Neo4j
Neo4j stores data as a web of connections, like a conspiracy board with red strings connecting everything.