Sub topic 13
Performance and Indexing for Recursive Queries
Assume you know SELECT, joins, grouping, self-joins, and basic subqueries. This chapter focuses on how recursive common table expressions (CTEs) use work tables, indexes, and query plans.
A recursive CTE does not usually jump directly from the root to every descendant. The database evaluates one generation at a time:
- It runs the anchor query and stores its rows in a working table.
- It runs the recursive member using the current working rows.
- It stores the new rows for the next iteration.
- It repeats until the recursive member returns no rows.
The cost depends on the number of iterations and the amount of work done in each iteration. A shallow tree with many children can be expensive. A deep tree with few children can also be expensive.
Index the recursive join
Consider an organizational tree:
CREATE TABLE employees (
id integer PRIMARY KEY,
name varchar(100) NOT NULL,
manager_id integer
);
CREATE INDEX employees_manager_id_idx
ON employees (manager_id);The recursive member usually joins a parent row to its children:
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, org.depth + 1
FROM employees AS e
JOIN org ON e.manager_id = org.id
)
SELECT id, name, depth
FROM org;The important lookup is e.manager_id = org.id. An index on employees.manager_id lets the database find direct reports without repeatedly scanning the entire employees table.
The anchor also needs an efficient lookup. Here, id is a primary key, so the root lookup is indexed automatically.
| Query part | Common lookup | Useful index |
|---|---|---|
| Anchor | `employees.id = 1` | Primary key on `id` |
| Recursive member | `employees.manager_id = org.id` | Index on `manager_id` |
Reduce rows early
Filters placed in the anchor limit the starting set. Filters in the recursive member limit later generations. Apply conditions as soon as they are logically safe.
For example, if inactive employees should not be traversed, filter them inside the recursive member:
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 1
AND active = true
UNION ALL
SELECT e.id, e.name, e.manager_id, org.depth + 1
FROM employees AS e
JOIN org ON e.manager_id = org.id
WHERE e.active = true
)
SELECT id, name, depth
FROM org;This prevents inactive branches from creating more working rows. An index such as (manager_id, active) may help when the table is large and the condition is selective. Always confirm the benefit with the database's plan tool, such as EXPLAIN.
Avoid repeated work
Recursive queries can multiply rows at every level. A manager with ten reports, each with ten reports, produces many rows after only a few levels. Return only the columns needed for later joins and the final result. Large path strings, JSON values, or wide payloads make every working-table row more expensive.
Use a depth limit when the business rule allows one:
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, org.depth + 1
FROM employees AS e
JOIN org ON e.manager_id = org.id
WHERE org.depth < 20
)
SELECT id, name, depth
FROM org;For frequently requested, mostly stable hierarchies, a closure table or materialized path can be faster than rebuilding the tree for every request. A recursive CTE is a good fit when relationships change often or the traversal rules vary.
Exercise
Which index most directly supports the recursive join in the employee example, and why?
Show answer
An index on employees(managerid), because each iteration searches for employees whose managerid matches the current parent id.