Recursive CTEs: Sequences, Hierarchies and Graph Walks
How WITH RECURSIVE builds a result step by step: the anchor and recursive parts, how execution stops, generating number and date series, walking a hierarchy down and up, tracking depth and paths, avoiding infinite loops in graphs, the CYCLE and SEARCH clauses, and dialect limits.
kvi5hnuCode Sprout team member14 min readOn this page
Some questions can't be answered with a fixed number of joins. "Who did Asha refer?" is one join from customers to itself. "Who did Asha refer, and who did they refer, and so on, however deep it goes?" needs one join per level, and you don't know in advance how many levels there are. The same problem appears with managers and their reports, categories and subcategories, parts made of other parts, and routes between cities.
A recursive CTE solves it. It's a common table expression that refers to itself: it starts from some rows and repeatedly derives new rows from the ones it just produced, until no new rows appear. This article explains how that works, then uses it to generate sequences, walk hierarchies in both directions, and explore graphs without getting stuck in loops.
The hierarchy examples use the referred_by column of the customers table, which holds the ID of the customer who referred them. Asha referred Ben and Chen, Ben referred Dana, and Chen referred Farah. Asha and Eli weren't referred by anyone.
The structure
A recursive CTE has two parts joined by UNION ALL:
WITH RECURSIVE cte_name (columns) AS (
anchor query -- runs once: the starting rows
UNION ALL
recursive query -- refers to cte_name: builds new rows from the previous ones
)
SELECT ... FROM cte_name;
The simplest example counts from 1 to 5:
-- Count from 1 to 5: an anchor row, then a step that runs until it returns nothing
WITH RECURSIVE numbers (n) AS (
SELECT 1 -- anchor: the starting row
UNION ALL
SELECT n + 1 -- recursive step: built from the previous rows
FROM numbers
WHERE n < 5 -- stop condition
)
SELECT n FROM numbers;
-- Two values carried from step to step: the Fibonacci sequence
WITH RECURSIVE fib (step, a, b) AS (
SELECT 1, 0, 1
UNION ALL
SELECT step + 1, b, a + b
FROM fib
WHERE step < 10
)
SELECT step, a AS fibonacci FROM fib;
n
---
1
2
3
4
5
(5 rows)
step | fibonacci
------+-----------
1 | 0
2 | 1
3 | 1
4 | 2
5 | 3
6 | 5
7 | 8
8 | 13
9 | 21
10 | 34
(10 rows)
Here's how the database runs the first query:
- Run the anchor (
SELECT 1). Its rows, here just the value 1, go into the result and into a working table. - Run the recursive query, with
numbersmeaning only the rows in the working table, not the whole result so far. From the row 1, it produces 2. - The new rows go into the result and replace the working table. Repeat step 2: from 2 it produces 3, then 4, then 5.
- From 5, the condition
n < 5is false, so the recursive query produces no rows. That's the stopping rule: the recursion ends as soon as a step produces nothing.
The result is everything that was produced, combined with UNION ALL. Despite its name, nothing calls itself: it's a loop that keeps feeding each step's output into the next step.
The second query carries several columns through the loop. Each step computes the next pair of Fibonacci numbers from the previous pair: (a, b) becomes (b, a + b). Any state you need from one step to the next must be a column of the CTE.
The stop condition is your responsibility
If the recursive query never stops producing rows, the query runs forever, or until the database runs out of memory or hits a limit. In the counting example, WHERE n < 5 is what ends the loop. Always check that every recursive query has something that eventually makes it return no rows: a counter limit, the bottom of a hierarchy, or a check that prevents revisiting rows.
Generating series
Counting is useful by itself: a recursive CTE can generate the rows that a report needs but the data doesn't have. Here are orders per day for a week, including days without orders:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Orders per day for the first week of March, including days with no orders
WITH RECURSIVE days (day) AS (
SELECT DATE '2026-03-01'
UNION ALL
SELECT day + 1
FROM days
WHERE day < DATE '2026-03-07'
)
SELECT d.day, COUNT(o.order_id) AS orders
FROM days d
LEFT JOIN orders o ON o.placed_on = d.day
GROUP BY d.day
ORDER BY d.day;
day | orders
------------+--------
2026-03-01 | 0
2026-03-02 | 1
2026-03-03 | 0
2026-03-04 | 0
2026-03-05 | 1
2026-03-06 | 0
2026-03-07 | 0
(7 rows)
The CTE produces one row per date from March 1 to March 7. Left-joining the orders to it gives every day a row, with 0 where there were no orders. A plain GROUP BY placed_on would show only March 2 and March 5, the days that have orders (article 19).
Many databases have a built-in function for this, which is simpler and faster when available: generate_series in PostgreSQL, GENERATE_SERIES in SQL Server 2022 and later, and a generate_series table-valued function in SQLite builds that include it. The recursive CTE works everywhere, with each database's date step (day + INTERVAL 1 DAY in MySQL, DATEADD(day, 1, day) in SQL Server, which also omits RECURSIVE), including MySQL, which has no series function. Article 41 builds calendars this way.
Walking a hierarchy down
The classic use of recursive CTEs is a tree stored as a parent column. Each customer row points to its parent with referred_by. To find everyone below a given customer, start from that customer and repeatedly find the rows whose parent is in the previous step:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Everyone Asha referred, directly or indirectly, with depth and path
WITH RECURSIVE referrals AS (
SELECT customer_id, name, 1 AS depth,
CAST(name AS TEXT) AS path
FROM customers
WHERE customer_id = 1 -- start at Asha
UNION ALL
SELECT c.customer_id, c.name, r.depth + 1,
r.path || ' > ' || c.name
FROM customers c
JOIN referrals r ON c.referred_by = r.customer_id -- children of the previous level
)
SELECT customer_id, depth, path
FROM referrals
ORDER BY path;
-- Walking up instead: Farah's chain of referrers
WITH RECURSIVE chain AS (
SELECT customer_id, name, referred_by, 0 AS steps_up
FROM customers
WHERE name = 'Farah Haddad'
UNION ALL
SELECT c.customer_id, c.name, c.referred_by, ch.steps_up + 1
FROM customers c
JOIN chain ch ON c.customer_id = ch.referred_by -- the parent of the previous row
)
SELECT steps_up, name
FROM chain
ORDER BY steps_up;
customer_id | depth | path
-------------+-------+------------------------------------
1 | 1 | Asha Rao
2 | 2 | Asha Rao > Ben Okafor
4 | 3 | Asha Rao > Ben Okafor > Dana Cruz
3 | 2 | Asha Rao > Chen Wei
6 | 3 | Asha Rao > Chen Wei > Farah Haddad
(5 rows)
steps_up | name
----------+--------------
0 | Farah Haddad
1 | Chen Wei
2 | Asha Rao
(3 rows)
In the first query:
- The anchor selects Asha, at depth 1, with a path that's just Asha's name.
- The recursive step joins
customersto the previous step's rows onc.referred_by = r.customer_id, finding the customers referred by someone found in the last step. Each new row getsdepth + 1and the parent's path extended with its own name.

The depth and path columns aren't needed for the recursion itself, but they're what make the result useful. depth gives the level in the tree, and path records the route from the top. Sorting by path lists each customer under their referrer, which is a quick way to display a tree.
Notice the CAST(name AS TEXT) in the anchor. In a recursive CTE, each column's type comes from the anchor. The path grows longer at each step, so its type must be able to hold the longer strings. More on this below.
Walking a hierarchy up
The second query goes the other way: from Farah up to the top. The only change is the join direction. Going down, a row's children are the customers whose referred_by is the row's ID. Going up, a row's parent is the customer whose ID is the row's referred_by:
-- down: children of the previous rows
JOIN referrals r ON c.referred_by = r.customer_id
-- up: the parent of the previous rows
JOIN chain ch ON c.customer_id = ch.referred_by
Going up, each step finds at most one row, because each customer has at most one referrer. The walk stops at Asha, whose referred_by is NULL, since customer_id = NULL matches nothing. That's the natural stop condition of a tree: you run out of parents going up, or out of children going down.
Graphs and cycles
A tree can't contain a loop. A graph can: city A has a route to B, B to C, and C back to A. Walking such a graph naively never ends, because the walk keeps going around the loop. Here's a small route map with a cycle (Pune to Leeds to York to Pune) and two ways to handle it:
-- A small route map with a loop: Pune -> Leeds -> York -> Pune
CREATE TABLE routes (src TEXT, dst TEXT);
INSERT INTO routes VALUES ('Pune', 'Leeds'), ('Leeds', 'York'),
('York', 'Pune'), ('Leeds', 'Oslo');
-- Track the path in an array and refuse to revisit a city
WITH RECURSIVE trips AS (
SELECT dst AS city, ARRAY['Pune', dst] AS path
FROM routes
WHERE src = 'Pune'
UNION ALL
SELECT r.dst, t.path || r.dst
FROM routes r
JOIN trips t ON r.src = t.city
WHERE r.dst <> ALL (t.path) -- not visited yet on this path
)
SELECT city, array_to_string(path, ' > ') AS route
FROM trips
ORDER BY cardinality(path), city;
-- UNION instead of UNION ALL: duplicate rows are discarded, so the walk stops
WITH RECURSIVE reachable (city) AS (
SELECT CAST('Pune' AS TEXT)
UNION
SELECT r.dst
FROM routes r
JOIN reachable re ON r.src = re.city
)
SELECT city FROM reachable ORDER BY city;
city | route
-------+---------------------
Leeds | Pune > Leeds
Oslo | Pune > Leeds > Oslo
York | Pune > Leeds > York
(3 rows)
city
-------
Leeds
Oslo
Pune
York
(4 rows)
Track the path. The first query keeps an array of the cities visited so far on each route, and only follows a route if its destination isn't already in the array (r.dst <> ALL (t.path), from article 22). From York, the route back to Pune is refused because Pune is in the path, so the walk ends. This works for any graph and also gives you the route. In databases without arrays, a delimited string does the same job, as in path NOT LIKE '%,' || r.dst || ',%'.
Use UNION instead of UNION ALL. With UNION, each step's new rows are compared with everything produced so far, and duplicates are discarded. When the walk comes back to Pune, the row ('Pune') already exists, so it's dropped, and the step after that has nothing to work from. This only stops the loop if the repeated rows are identical. Add a hops or path column that changes at every step, and no row is ever a duplicate, so UNION no longer helps.
The CYCLE and SEARCH clauses
The SQL standard has two clauses that handle cycle detection and ordering for you. PostgreSQL has supported them since version 14, and Oracle has its own versions:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
CREATE TABLE routes (src TEXT, dst TEXT);
INSERT INTO routes VALUES ('Pune', 'Leeds'), ('Leeds', 'York'),
('York', 'Pune'), ('Leeds', 'Oslo');
-- PostgreSQL 14+: the standard CYCLE clause marks and stops cycles
WITH RECURSIVE trips (city, hops) AS (
SELECT CAST('Pune' AS TEXT), 0
UNION ALL
SELECT r.dst, t.hops + 1
FROM routes r
JOIN trips t ON r.src = t.city
) CYCLE city SET is_cycle USING visited
SELECT city, hops, is_cycle
FROM trips
ORDER BY hops, city;
-- The standard SEARCH clause: depth-first order for an indented tree
WITH RECURSIVE tree AS (
SELECT customer_id, name, 0 AS level
FROM customers
WHERE referred_by IS NULL
UNION ALL
SELECT c.customer_id, c.name, t.level + 1
FROM customers c
JOIN tree t ON c.referred_by = t.customer_id
) SEARCH DEPTH FIRST BY customer_id SET ordering
SELECT repeat(' ', level) || name AS referral_tree
FROM tree
ORDER BY ordering;
city | hops | is_cycle
-------+------+----------
Pune | 0 | f
Leeds | 1 | f
Oslo | 2 | f
York | 2 | f
Pune | 3 | t
(5 rows)
referral_tree
----------------------
Asha Rao
Ben Okafor
Dana Cruz
Chen Wei
Farah Haddad
Eli Novak
(6 rows)
CYCLE city SET is_cycle USING visitedmakes PostgreSQL track thecityvalues on each path in an extra array column calledvisited(it appears withSELECT *; this query just doesn't select it). When a row would repeat a city already on its path, the row is still produced but marked withis_cycle = true, and the walk doesn't continue from it. Here, the trip back to Pune after 3 hops is reported as a cycle and stops there.SEARCH DEPTH FIRST BY customer_id SET orderingadds a column,ordering, that sorts the rows depth first: each customer is followed by all of their descendants before the next sibling.ORDER BY orderingthen prints the tree in the familiar indented layout.SEARCH BREADTH FIRSTorders level by level instead.
The query starts from every customer without a referrer, so Eli appears as a second root with no one below them.
Rules and errors
The recursive part of a recursive CTE has restrictions, and the column types need care:
-- Aggregates aren't allowed in the recursive step
WITH RECURSIVE bad AS (
SELECT 1 AS x
UNION ALL
SELECT COUNT(*) FROM bad
)
SELECT x FROM bad;
-- The recursive step may refer to the CTE only once
WITH RECURSIVE bad2 (n) AS (
SELECT 1
UNION ALL
SELECT a.n + 1 FROM bad2 a JOIN bad2 b ON a.n = b.n WHERE a.n < 3
)
SELECT n FROM bad2;
-- A column's type is fixed by the anchor: text grows past VARCHAR(5)
WITH RECURSIVE s (word) AS (
SELECT CAST('ab' AS VARCHAR(5))
UNION ALL
SELECT word || 'ab' FROM s WHERE length(word) < 6
)
SELECT word FROM s;
psql:/workspace/solution.sql:7: ERROR: aggregate functions are not allowed in a recursive query's recursive term
LINE 4: SELECT COUNT(*) FROM bad
^
psql:/workspace/solution.sql:15: ERROR: recursive reference to query "bad2" must not appear more than once
LINE 4: SELECT a.n + 1 FROM bad2 a JOIN bad2 b ON a.n = b.n WHER...
^
psql:/workspace/solution.sql:23: ERROR: recursive query "s" column 1 has type character varying(5) in non-recursive term but type character varying overall
LINE 2: SELECT CAST('ab' AS VARCHAR(5))
^
HINT: Cast the output of the non-recursive term to the correct type.
- No aggregates in the recursive step. Each step works on the previous step's rows, so "count the rows so far" has no meaning. Aggregate in the main query instead.
GROUP BY,DISTINCT, window functions and, in most databases,ORDER BYandLIMITare restricted in the recursive step for the same reason. - The CTE may appear only once in the recursive step. You can't join it to itself there. An outer join where the CTE is on the optional side is also rejected.
- The anchor decides the column types. The anchor's
wordisVARCHAR(5), but the recursive step produces longer, unlimited text, and PostgreSQL rejects the mismatch. Cast in the anchor to a type wide enough for every step, such asTEXT, orVARCHAR(1000)in databases withoutTEXT. MySQL instead keeps the anchor's type and, in strict mode, fails with a "data too long" error once a value outgrows it.
Dialect differences
| Database | Keyword | Notes |
|---|---|---|
| PostgreSQL | WITH RECURSIVE | No built-in depth limit. CYCLE and SEARCH since version 14. |
| MySQL 8.0+ | WITH RECURSIVE | Stops after cte_max_recursion_depth steps (1000 by default). |
| SQLite | WITH RECURSIVE | Also allows ORDER BY and LIMIT in the recursive step. |
| SQL Server | WITH (no RECURSIVE) | Stops after 100 levels by default. Change with OPTION (MAXRECURSION n), where 0 means no limit. |
| Oracle | WITH (no RECURSIVE) | Requires a column list after the CTE name. Has SEARCH and CYCLE clauses, and the older CONNECT BY syntax (article 48). |
In SQL Server and Oracle, the anchor and recursive parts must be combined with UNION ALL. PostgreSQL, MySQL and SQLite also accept UNION.
The depth limits in MySQL and SQL Server are a safety net, not a stop condition. A query that hits them fails with an error rather than returning a partial result. PostgreSQL has no such limit, so a runaway recursive query keeps going until it runs out of memory or disk, or until a statement timeout cancels it.
Performance
A recursive CTE does one round of work per level. For a hierarchy, the number of levels is usually small even when the number of rows is large: a company with 100,000 employees might have 10 levels of management. What matters is that each step's join is fast, so index the join column: referred_by when walking down, the primary key when walking up.
Paths stored as arrays or strings grow at every step and cost memory on deep or wide graphs. For a graph with many routes between the same nodes, the number of distinct paths can grow exponentially, even with cycle protection. Restrict the depth with a hops < n condition when you only need short paths.
What's current
- PostgreSQL 14 added the standard
SEARCHandCYCLEclauses, so cycle detection and depth-first or breadth-first ordering no longer need hand-written arrays. - SQL Server 2022 added
GENERATE_SERIES, so it no longer needs a recursive CTE to generate a series of numbers. - Recursive CTEs are available in every major database: PostgreSQL, SQL Server, Oracle (11g Release 2 and later), SQLite (3.8.3 and later), MySQL (8.0 and later) and MariaDB (10.2 and later).
Common questions
Why is it called recursive if it's really a loop? Because the CTE is defined in terms of itself. It's executed iteratively, one step at a time, each step using only the previous step's rows.
How does a recursive CTE know when to stop?
It stops when a step returns no rows. The stop condition comes from your WHERE clause or from the data, for example running out of children in a tree.
What's the difference between UNION and UNION ALL in a recursive CTE?
UNION ALL keeps every row. UNION discards rows that duplicate any row produced so far, which can stop a cycle, but only if repeated rows are exactly identical.
How do I limit the depth?
Carry a level column and add WHERE level < n in the recursive step.
Can I use ORDER BY in a recursive CTE?
Sort in the main query. For tree order, build a path column and sort by it, or use SEARCH DEPTH FIRST in PostgreSQL and Oracle.
Why do I get a type mismatch error? The anchor's columns fix the types, and a recursive step produced a value of a different or wider type. Cast the anchor's columns to the type you need.
Can a recursive CTE be used with other CTEs?
Yes. With WITH RECURSIVE, all the CTEs in the clause may be recursive or not. Only the ones that refer to themselves are actually recursive.
Should I use a recursive CTE or CONNECT BY in Oracle?
Both work. CONNECT BY is Oracle-only and shorter for simple trees. The recursive CTE is standard and portable. Article 48 compares them.
Summary
- A recursive CTE has an anchor query and a recursive query joined by
UNION ALL. The anchor runs once, and the recursive query runs repeatedly on the previous step's rows until it returns none. - Use it to generate series of numbers or dates, to walk trees down (children) or up (parents), and to explore graphs.
- Carry extra columns, such as depth and path, to make the result useful, and cast them in the anchor, because the anchor fixes the column types.
- Graphs with cycles need protection: track visited nodes in a path, use
UNIONwhen repeated rows are identical, or use theCYCLEclause in PostgreSQL 14+. SEARCH DEPTH FIRSTandBREADTH FIRSTgive tree ordering in PostgreSQL 14+.- SQL Server and Oracle omit the
RECURSIVEkeyword. MySQL stops at 1000 steps and SQL Server at 100 levels by default. PostgreSQL has no limit.
Practice questions
Write a recursive CTE that returns the even numbers from 2 to 20.
Answer
WITH RECURSIVE evens (n) AS (
SELECT 2
UNION ALL
SELECT n + 2 FROM evens WHERE n < 20
)
SELECT n FROM evens;
It returns 2, 4, ..., 20: ten rows. The step from 20 produces nothing because 20 < 20 is false.
What's wrong with this query? WITH RECURSIVE n (i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n) SELECT i FROM n WHERE i <= 10;
Answer
The recursive step has no stop condition. The WHERE i <= 10 in the main query filters the result, but it doesn't stop the recursion, which keeps generating numbers until it fails or a limit is hit (1000 steps in MySQL, 100 in SQL Server, none in PostgreSQL). Move the condition into the recursive step: SELECT i + 1 FROM n WHERE i < 10.
Write a query that lists every customer referred, directly or indirectly, by Chen Wei (customer 3), with their depth below Chen.
Answer
WITH RECURSIVE below (customer_id, name, depth) AS (
SELECT customer_id, name, 1
FROM customers
WHERE referred_by = 3
UNION ALL
SELECT c.customer_id, c.name, b.depth + 1
FROM customers c
JOIN below b ON c.referred_by = b.customer_id
)
SELECT name, depth FROM below ORDER BY depth, name;
It returns Farah Haddad at depth 1. Here the anchor starts at Chen's direct referrals rather than Chen, so Chen isn't in the result.
A recursive walk of a route map with a cycle uses UNION instead of UNION ALL to stop the loop, but it still runs until the depth limit. The CTE has the columns (city, hops). Why doesn't UNION help?
Answer
UNION discards only rows that are identical to a row already produced. Because hops increases at every step, a row that returns to a city has a different hops value, such as ('Pune', 3) instead of ('Pune', 0), so it's not a duplicate and the walk continues around the loop. Track the visited cities in a path and refuse to revisit them, or use the CYCLE clause.
In SQL Server, a recursive CTE that walks a 150-level hierarchy fails with an error about the maximum recursion. Why, and how do you fix it?
Answer
SQL Server stops recursive CTEs at 100 levels by default. Add OPTION (MAXRECURSION 200) to the end of the statement, or OPTION (MAXRECURSION 0) to remove the limit, which is only safe when you're sure the recursion ends.
Previous: Common Table Expressions (WITH): Writing Readable SQL in Steps

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.