Sub topic 8
WITH RECURSIVE versus WITH: Differences Across Databases
This chapter assumes you can write a basic CTE and a recursive CTE with an anchor member and a recursive member, as in the earlier chapters. You should also know what UNION ALL does. The SQL standard defines recursive CTEs, but each database implements its own subset and adds its own settings. A recursive query that runs in one engine can fail in another because of a missing keyword, a type mismatch, or a recursion limit.
The keyword question: RECURSIVE or not
The standard writes recursive CTEs as WITH RECURSIVE. Databases split into two camps.
- Keyword required. PostgreSQL, MySQL 8.0+, and MariaDB reject a self-referencing CTE unless you write
WITH RECURSIVE. - Keyword absent or optional. SQL Server and Oracle use plain
WITHfor both kinds, andRECURSIVEis a syntax error in them. SQLite acceptsRECURSIVEbut treats any CTE that refers to itself as recursive anyway.
Here is the same counter in each camp. This version runs in PostgreSQL, MySQL 8.0+, MariaDB, and SQLite:
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;This version runs in SQL Server. Note the leading semicolon, which is explained below:
;WITH numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;This version runs in Oracle 11g Release 2 and later. Oracle needs FROM dual because it requires a FROM clause in every SELECT:
WITH numbers (n) AS (
SELECT 1 FROM dual
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;In PostgreSQL, RECURSIVE applies to the whole WITH list, not to one CTE. If you write WITH RECURSIVE a AS (...), b AS (...), either CTE may refer to itself, and a non-recursive CTE in the same list is still allowed. You do not need a second keyword for each CTE.
Version and feature summary
| Database | Recursive CTEs since | Keyword | Recursion limit | Built-in cycle help |
|---|---|---|---|---|
| PostgreSQL | 8.4 | `WITH RECURSIVE` | None | `SEARCH` and `CYCLE` from 14 |
| MySQL | 8.0 | `WITH RECURSIVE` | `cte_max_recursion_depth`, default 1000 | None |
| MariaDB | 10.2.2 | `WITH RECURSIVE` | `max_recursive_iterations` setting | Limited, check your version |
| SQLite | 3.8.3 | Optional | None, use `LIMIT` | None |
| SQL Server | 2005 | `WITH` | `MAXRECURSION`, default 100 | None |
| Oracle | 11g Release 2 | `WITH` | None | `SEARCH` and `CYCLE` |
Check your exact version before relying on a row. The table is a guide, and defaults can change between releases.
Recursion limits and runaway queries
The earlier chapter on termination covered writing a stopping condition. The safety nets differ by engine, and you should know which one you have.
- PostgreSQL has no depth limit. A query with no stopping condition runs until it fills memory or disk, or until you cancel it. Set
statement_timeoutfor sessions that run ad hoc recursive queries. - MySQL stops with an error when the recursion depth passes
cte_max_recursion_depth. You can raise it for one session:
SET SESSION cte_max_recursion_depth = 10000;- SQL Server stops after 100 recursion levels with error 530. You change the limit with a query hint at the end of the outer statement. The value
0removes the limit:
;WITH numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 500
)
SELECT n FROM numbers
OPTION (MAXRECURSION 600);- SQLite has no depth limit, but you can cap the row count with
LIMITinside the recursive query. SQLite stops generating rows once the limit is reached, so this is a valid way to stop a counter.
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers
LIMIT 5
)
SELECT n FROM numbers;A depth limit does not replace a termination condition. It turns an infinite loop into an error, and some engines use it as a convenience instead. A query that needs more rows than the limit allows will fail even though it is correct.
Cycle protection: array tricks versus built-in clauses
The Topic Spine example guards against cycles by keeping a path array. That relies on PostgreSQL array syntax, so it does not port to MySQL, SQL Server, or SQLite. There you build the path as a string instead, for example by concatenating ids with delimiters, and test it with LIKE or INSTR.
PostgreSQL 14 and later, and Oracle, add SEARCH and CYCLE clauses that handle this for you. Here is the PostgreSQL form:
WITH RECURSIVE walk(id) AS (
SELECT 1
UNION ALL
SELECT e.to_id
FROM walk w
JOIN edges e ON e.from_id = w.id
)
CYCLE id SET is_cycle USING path
SELECT id, path
FROM walk
WHERE NOT is_cycle;CYCLE id tells the engine to watch the id column. It adds an is_cycle flag and a path column holding the visited values. When a row repeats a value already on its path, the engine marks it and does not expand it any further. The WHERE NOT is_cycle filter then hides the repeated row. The Oracle syntax is similar but uses CYCLE id SET is_cycle TO 'Y' DEFAULT 'N'.
Restrictions on the recursive member
All engines require the recursive member to refer to the CTE name in a limited way, and some add more rules. The common ground:
- The anchor member must come first, and it must not refer to the CTE.
- Members are joined by
UNION ALL. SQL Server and Oracle requireUNION ALLfor recursion. PostgreSQL, MySQL, and SQLite also allowUNION, which removes duplicate rows and can stop some cycles for free. - The recursive member refers to the CTE once, in its
FROMclause.
MySQL is stricter than most. In the recursive member, it does not allow aggregate functions, window functions, GROUP BY, or DISTINCT. The CTE name also cannot appear on the right side of a LEFT JOIN. PostgreSQL forbids the same self-reference placements. If a rewrite fails with a message about "recursive reference", the cause is usually one of these rules. In that case, move the aggregation to the outer query, or compute it in a separate non-recursive CTE that reads the recursive result.
Column lists and type matching
Column names for a recursive CTE come from the anchor member, or from an explicit column list after the CTE name. Oracle requires the explicit list, and it raises an error without one. PostgreSQL, MySQL, SQL Server, and SQLite make it optional. Writing it everywhere costs little and keeps the query portable.
Types are the next trap. The result column takes its type from the anchor member, and every recursive step must fit that type.
- SQL Server demands the types and lengths match exactly. An anchor of
'a'is typedvarchar(1), and the recursive member then fails when it appends text to it. The error says the types do not match between the anchor and the recursive part. - PostgreSQL rejects a mismatch of lengths too, with a message that the column "has type character varying(50) in non-recursive term but type character varying overall".
- MySQL silently takes the width of the anchor and may truncate strings, or raise an error in strict mode.
The fix is the same everywhere: cast the anchor to the widest type you need.
WITH RECURSIVE paths(id, path) AS (
SELECT id, CAST(name AS VARCHAR(500))
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, CAST(p.path || ' > ' || e.name AS VARCHAR(500))
FROM employees e
JOIN paths p ON e.manager_id = p.id
)
SELECT id, path FROM paths;This version uses the || concatenation operator, which works in PostgreSQL, SQLite, and Oracle. MySQL treats || as logical OR by default, so use CONCAT(p.path, ' > ', e.name) there. SQL Server uses + or CONCAT. Run it on SQL Server by removing the RECURSIVE keyword and replacing || with CONCAT.
Other syntax differences that affect CTEs
These points are not about recursion, but they cause the same kind of porting failures.
- Statement terminator in SQL Server.
WITHis also used for table hints, so SQL Server requires the statement before a CTE to end with a semicolon. This is why examples write;WITH. Ending every statement with a semicolon avoids the problem. ORDER BYinside a CTE. SQL Server rejectsORDER BYin a CTE unless it is paired withTOPorOFFSET. PostgreSQL and MySQL allow it, but the order is not guaranteed to survive into the outer query.- Materialization hints. PostgreSQL 12 and later accepts
MATERIALIZEDandNOT MATERIALIZED. SQLite 3.35 and later accepts the same keywords. MySQL, SQL Server, and Oracle do not. SQL Server inlines every CTE like a view, so a CTE referenced twice is computed twice. - Data-modifying CTEs. Only PostgreSQL lets
INSERT,UPDATE, andDELETEappear inside aWITHclause. SQL Server lets a CTE feed an outerINSERT,UPDATE,DELETE, orMERGE, but the CTE itself contains only aSELECT. - Date and string functions.
date_truncin the monthly sales example is PostgreSQL only. MySQL usesDATE_FORMAT, SQL Server usesDATETRUNC(2022 and later) orDATEFROMPARTS, and Oracle usesTRUNC.
Oracle's alternative: CONNECT BY
Oracle predates recursive CTEs with its own hierarchy syntax. You may meet it in older code:
SELECT id, name, LEVEL - 1 AS depth
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR id = manager_id
ORDER SIBLINGS BY name;START WITH is the anchor, CONNECT BY PRIOR is the join to the parent row, and LEVEL is the depth. It is shorter than a recursive CTE for simple trees but works only in Oracle. A recursive CTE is the portable choice, and Oracle supports it, so prefer the CTE for new code that might move between databases.
A portability checklist
Work through this list when you move a recursive query to another engine.
- Add or remove
RECURSIVEto match the target. - Write an explicit column list after the CTE name.
- Cast the anchor's columns to the widest type the recursion will produce.
- Replace array-based cycle guards with string paths or a built-in
CYCLEclause. - Check the engine's recursion limit and set it deliberately.
- Confirm that functions, concatenation, and date arithmetic exist in the target dialect.
- Re-run with a cyclic dataset to prove the guard works.
Exercises
Exercise
A recursive CTE written with WITH RECURSIVE runs in PostgreSQL. You move it to SQL Server and it fails at the first line. What is the first change to make, and what other two things in SQL Server can still stop the query from running to completion?
Show answer
Remove the RECURSIVE keyword, because SQL Server uses plain WITH, and put a semicolon before the statement. After that, check the anchor and recursive member types, which must match exactly (cast the anchor to the widest type). Also check the recursion depth: SQL Server stops at 100 levels by default, so deeper hierarchies need OPTION (MAXRECURSION n) on the outer query.
Exercise
A MySQL 8 recursive query that counts to 5000 fails with an error about the recursion depth, but the same query returns correctly in PostgreSQL. Why, and how do you fix it in MySQL?
Show answer
MySQL limits recursion with cte_max_recursion_depth, whose default is 1000. PostgreSQL has no such limit. Raise the limit for the session with SET SESSION cte_max_recursion_depth = 10000;, or restructure the query to need fewer iterations.