Sub topic 14
When not to use a recursive CTE
This chapter assumes you can write a recursive CTE with an anchor member and a recursive member. It also assumes you know the UNION ALL and cycle-guard patterns from the earlier chapters. Recursive CTEs are a good default for hierarchies and graphs, but they are not always the best tool. This chapter covers the cases where another design is better, and how to decide.
Where recursive CTEs struggle
A recursive CTE walks the data one level at a time. Each iteration runs a join against the working table, which holds only the rows found in the previous iteration. That model has three costs.
- Cost grows with depth and fan-out. A tree 20 levels deep needs 20 iterations. Every read repeats the full walk.
- The work is repeated. If a dashboard asks for the subtree of the same manager 10,000 times a day, the database walks that subtree 10,000 times.
- Reads cost more than writes. If the hierarchy changes rarely and is queried constantly, you are paying at read time for something you could pay for once at write time.
None of this makes recursive CTEs wrong. It means you should ask how often the query runs, how deep the data goes, and how often the data changes.
Alternative 1: Oracle CONNECT BY
Oracle has a native hierarchical query clause, CONNECT BY, that predates recursive CTEs. Oracle also supports the standard recursive WITH syntax (the recursive subquery factoring clause) since version 11gR2.
SELECT employee_id,
last_name,
LEVEL AS depth,
SYS_CONNECT_BY_PATH(last_name, '/') AS path
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;START WITH plays the role of the anchor member. CONNECT BY PRIOR describes how a child row relates to its parent row. LEVEL gives the depth, and SYS_CONNECT_BY_PATH builds the path string. Adding NOCYCLE makes Oracle skip rows that would form a loop, and CONNECT_BY_ISCYCLE flags them.
The syntax is compact, but it only works in Oracle. Choose it when you are committed to Oracle and want the shorter form. Choose the standard recursive CTE when the query must run on several databases.
Alternative 2: Closure tables
A closure table stores every ancestor-descendant pair as a row. A tree with a root, a child, and a grandchild stores these pairs:
| ancestor_id | descendant_id | depth |
|---|---|---|
| 1 | 1 | 0 |
| 1 | 2 | 1 |
| 1 | 3 | 2 |
| 2 | 2 | 0 |
| 2 | 3 | 1 |
| 3 | 3 | 0 |
Every node also has a row pointing to itself with depth 0. Finding all descendants of a node becomes a plain indexed lookup, with no recursion.
CREATE TABLE employee_closure (
ancestor_id INTEGER NOT NULL,
descendant_id INTEGER NOT NULL,
depth INTEGER NOT NULL,
PRIMARY KEY (ancestor_id, descendant_id)
);
CREATE INDEX idx_closure_descendant
ON employee_closure (descendant_id, ancestor_id);
-- Everyone under employee 1, with depth
SELECT e.id, e.name, c.depth
FROM employee_closure c
JOIN employees e ON e.id = c.descendant_id
WHERE c.ancestor_id = 1
AND c.depth > 0
ORDER BY c.depth, e.name;The read is one join over an index. A subtree rollup is just a GROUP BY over the closure rows.
The cost moves to writes. When you insert a new node under a parent, you must insert one closure row for each ancestor of the parent, plus the self row:
INSERT INTO employee_closure (ancestor_id, descendant_id, depth)
SELECT c.ancestor_id, 4, c.depth + 1
FROM employee_closure c
WHERE c.descendant_id = 3 -- the new node's parent
UNION ALL
SELECT 4, 4, 0;Moving a subtree is harder. You must delete the old ancestor links for every node in the moved subtree and insert the new ones. The table also grows. A chain of depth d stores about d * (d + 1) / 2 rows for that chain alone, so deep trees make it large.
Alternative 3: Materialized paths
A materialized path stores each node's full path in a column on the node itself, for example /1/2/3/.
CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
path TEXT NOT NULL -- for example '/1/2/3/'
);
CREATE INDEX idx_categories_path ON categories (path text_pattern_ops);
-- All descendants of category 2 (PostgreSQL)
SELECT id, name
FROM categories
WHERE path LIKE '/1/2/%'
AND id <> 2;The text_pattern_ops operator class is PostgreSQL-specific. It lets a B-tree index serve a LIKE 'prefix%' search when the database does not use the C collation. Other databases have their own equivalents, so check how yours indexes prefix matches.
Depth is the number of separators in the path. Finding the ancestors of a node means splitting the path string, which is awkward in SQL. Moving a subtree means rewriting the path of every node below it. Paths made of ids also cannot enforce referential integrity, because the database does not know that each id inside the string refers to a real row.
Other options
Two more designs appear often.
- Nested sets store a left and right number on each node so that a subtree is a range. Reads are fast, but almost any insert or move renumbers many rows. They suit data that is almost read-only.
- Native types and extensions include PostgreSQL's
ltreeextension for label paths, and graph databases or graph extensions for data where relationships are the main concern.
Comparing the options
| Design | Subtree read | Insert | Move subtree | Extra storage | Portable |
|---|---|---|---|---|---|
| Recursive CTE on parent_id | Walks level by level | One row | Update one row | None | Yes |
| Oracle CONNECT BY | Walks level by level | One row | Update one row | None | Oracle only |
| Closure table | Indexed join | Rows per ancestor | Rewrite many rows | Large for deep trees | Yes |
| Materialized path | Prefix scan | One row | Rewrite subtree paths | One column | Mostly |
| Nested sets | Range scan | Renumber many rows | Renumber many rows | Two columns | Yes |
Decision criteria
Use these questions in order.
- Is the data a graph with cycles, or edges that change shape? Closure tables and paths assume a tree. A recursive CTE with a cycle guard handles general graphs.
- How often does it change? Frequent moves favor the plain
parent_idcolumn with a recursive CTE. Rare changes favor a precomputed design. - How often is it read, and how deep is it? Many reads of deep trees favor a closure table. A few reads of a shallow tree rarely justify the extra table.
- Which database do you run?
CONNECT BYis only an option on Oracle. Path-prefix indexing differs between systems. - Is the result needed once or repeatedly? For one-off reports, a recursive CTE is the lowest-effort choice. For a hot path, measure first.
A middle route is to keep parent_id as the source of truth and build a precomputed structure from it. A materialized view or a scheduled job can fill a closure table with a recursive CTE, so you get fast reads without hand-maintaining the rows on every write.
-- PostgreSQL: rebuild a closure table from parent_id
TRUNCATE employee_closure;
INSERT INTO employee_closure (ancestor_id, descendant_id, depth)
WITH RECURSIVE tree AS (
SELECT id AS ancestor_id, id AS descendant_id, 0 AS depth
FROM employees
UNION ALL
SELECT t.ancestor_id, e.id, t.depth + 1
FROM tree t
JOIN employees e ON e.manager_id = t.descendant_id
)
SELECT ancestor_id, descendant_id, depth FROM tree;The anchor seeds one self row per employee. Each iteration then extends every chain by one level, which produces every ancestor-descendant pair. This assumes the data is a tree. If the data could contain a cycle, add the path check from the earlier chapter.
Common mistakes
- Choosing by habit. People pick a closure table because a blog post recommended it, then discover their tree has 200 rows and never needed it.
- Forgetting the write path. A closure table or path column that is not updated on every insert, delete, and move quietly returns wrong answers.
- Storing paths without a delimiter at both ends. The path
/1/2also matches/1/20with a prefix search unless you end each path with/. - Ignoring depth limits. A precomputed design does not remove the need to think about cycles. A cycle inserted into the source data can still break the rebuild query.
Exercise
A product catalog has 50,000 categories in a tree that is 6 levels deep. Categories almost never move, but the storefront asks for "all products in this category and its subcategories" thousands of times a minute. Which design would you choose, and what must you do when a category is added?
Show answer
Use a closure table, or a materialized path if you only need descendant lookups. The query runs often and the data rarely changes, so paying the cost at write time is worthwhile and reads become an indexed lookup. With a closure table, adding a category means inserting one row for each ancestor of its parent plus a self row with depth 0, in the same transaction as the category insert. Keep parent_id as the source of truth so the table can be rebuilt with a recursive CTE.
Exercise
Your team runs a quarterly report that totals costs over an org chart of 800 people on PostgreSQL. A colleague proposes a closure table. Give one reason to keep the recursive CTE.
Show answer
The query runs rarely on a small tree, so the recursive CTE is fast enough. A closure table would add a table, an index, and write logic that must stay correct on every hire, departure, and reporting change. The extra complexity has no payoff at this size and frequency.