IT lexicon › Database › Recursive CTE

Recursive CTE

Database På svenska → Updated: 2026-05-27

SQL feature: WITH RECURSIVE syntax for a recursive query. Use: traverse tree structures (org hierarchy, category trees), graph walks, generate number series.

Classic example: find all subordinates of a manager.
WITH RECURSIVE subs AS (SELECT id, name, boss_id FROM employees WHERE id = ? UNION SELECT e.id, e.name, e.boss_id FROM employees e JOIN subs s ON e.boss_id = s.id) SELECT * FROM subs;
SQL standard since 1999 but PostgreSQL has a solid implementation; MySQL got it first in 8.0 (2018). Risk: infinite recursion without termination condition → the planner can't stop, query hangs. Modern graph databases (Neo4j, Memgraph) do graph traversals more efficiently but SQL CTEs are enough for most tree queries.

← Back to the lexicon