Sub topic 14
When Not to Use a Recursive CTE
Assume you know SELECT, joins, GROUP BY, and self-joins. A recursive common table expression (CTE) is useful when each step depends on rows found in the previous step. It is not always the best design for storing or querying a hierarchy.
A recursive CTE calculates a result when you ask for it. That flexibility has a cost: the database may repeatedly join tables, build working rows, and repeat the same traversal. Consider another design when reads are frequent, the hierarchy changes rarely, or the maximum depth is large.
Choose based on the workload
| Need | Often a better choice | Reason |
|---|---|---|
| Frequent ancestor and descendant queries | Closure table | Stores every relationship directly |
| Simple tree listing and prefix searches | Materialized path | A path identifies each node's position |
| Oracle-specific hierarchy queries | `CONNECT BY` | Uses Oracle's native hierarchy syntax |
| Small, changing hierarchy | Recursive CTE | Avoids maintaining extra derived data |
A recursive CTE is often the simplest starting point. Alternatives usually trade simpler reads for more complicated writes or additional storage.
Closure tables for repeated relationship queries
A closure table stores one row for every ancestor-descendant pair. It can also store the distance between them.
For example, if A contains B, and B contains C, the table stores A → B, B → C, and A → C. Finding all descendants becomes an ordinary indexed query instead of a recursive traversal.
CREATE TABLE category_closure (
ancestor_id INTEGER NOT NULL,
descendant_id INTEGER NOT NULL,
distance INTEGER NOT NULL,
PRIMARY KEY (ancestor_id, descendant_id)
);
SELECT descendant_id, distance
FROM category_closure
WHERE ancestor_id = 10
ORDER BY distance, descendant_id;This design makes reads fast and predictable. Moving a subtree requires updating many closure rows, so it is a poor fit when nodes move often.
Materialized paths for tree-shaped data
A materialized path stores the identifiers from the root to each node. A row might contain /1/4/9/. Descendants can then be found with a prefix condition.
CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
path VARCHAR(500) NOT NULL
);
SELECT id, name
FROM categories
WHERE path LIKE '/1/4/%'
ORDER BY path;This approach works well when the hierarchy is a tree and path-prefix searches are supported efficiently. Moving a node usually requires changing the path of that node and every descendant. Use a path format with unambiguous separators. Otherwise, a search for /4/ might also match an unrelated identifier such as 40.
Some systems offer specialized path types or indexes. Check your database before relying on a leading-prefix search for large tables.
Native hierarchy syntax
Oracle provides CONNECT BY, which expresses parent-child traversal without a recursive CTE. It includes features for identifying the current level, the root, and the path.
SELECT employee_id,
name,
LEVEL AS depth,
SYS_CONNECT_BY_PATH(name, '/') AS path
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;Use this when your application is already tied to Oracle and the team understands the syntax. A recursive CTE is usually easier to move between PostgreSQL, MySQL, SQLite, and SQL Server.
A practical decision
Prefer a recursive CTE when the hierarchy is moderate, changes regularly, and the query needs vary. Prefer a closure table when predictable, fast relationship queries matter more than simple updates. Prefer a materialized path when prefix searches fit the data model. Use CONNECT BY when Oracle compatibility is more important than portability.
Test the chosen design with realistic depth, branching, row counts, and update frequency. An alternative that is faster for reads may be slower and more error-prone during writes.
Exercise
A product category tree changes daily, but the application queries ancestors and descendants thousands of times per minute. Which alternative should you investigate first, and what trade-off must you plan for?
Show answer
Investigate a closure table first. It can make relationship reads direct and index-friendly, but moving or deleting a subtree requires maintaining many derived ancestor-descendant rows.