Sub topic 11
Syntax and limits across PostgreSQL, MySQL, SQLite, and SQL Server
This chapter assumes you can write a basic recursive CTE (anchor member, recursive member, UNION ALL) and that you know how a query terminates when the recursive member returns no new rows. It covers where the four most common engines differ and how to adjust a query when you move it between them.
What stays the same
The core pattern is standard SQL and works in every engine covered here. An anchor query seeds a working table. The recursive member reads the previous iteration's rows, and the database repeats until an iteration produces nothing. The differences are in keywords, limits, available functions, and a few extras.
| Feature | PostgreSQL | MySQL (8.0+) | SQLite | SQL Server |
|---|---|---|---|---|
| `RECURSIVE` keyword | Required | Required | Required | Not allowed |
| Default recursion limit | None | 1000 (`cte_max_recursion_depth`) | None | 100 (`MAXRECURSION`) |
| Array type for paths | Yes (`ARRAY[...]`) | No | No | No |
| Built-in `CYCLE` / `SEARCH` | PostgreSQL 14+ | No | No | No |
| `UNION` (dedup) in recursion | Yes | Yes | Yes | No, only `UNION ALL` |
The RECURSIVE keyword
PostgreSQL, MySQL, and SQLite require WITH RECURSIVE as soon as any CTE in the list refers to itself. SQL Server rejects the keyword and uses plain WITH.
-- PostgreSQL, MySQL 8, SQLite
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n WHERE i < 10
)
SELECT i FROM n;-- SQL Server
WITH n AS (
SELECT 1 AS i
UNION ALL
SELECT i + 1 FROM n WHERE i < 10
)
SELECT i FROM n;In PostgreSQL, MySQL, and SQLite you write RECURSIVE once, right after WITH, even when only one of several CTEs is recursive. Non-recursive CTEs in the same list are still allowed.
A second SQL Server detail: if the WITH clause is not the first statement in a batch, the previous statement must end with a semicolon. A common habit is to write ;WITH ... to avoid the error "Incorrect syntax near the keyword 'WITH'".
Recursion limits
An accidental infinite loop is a real risk, so some engines add a safety limit. The limits differ, and so does what happens when you reach them.
SQL Server: 100 levels by default
SQL Server stops after 100 recursion levels and raises error 530. You change the limit per query with the MAXRECURSION hint at the end of the outer statement. The value 0 removes the limit entirely.
WITH n AS (
SELECT 1 AS i
UNION ALL
SELECT i + 1 FROM n WHERE i < 1000
)
SELECT i FROM n
OPTION (MAXRECURSION 1000);The limit counts recursion levels, not rows. A series from 1 to 1000 needs 999 levels, so a limit of 1000 is enough. The hint accepts values from 0 to 32767. Setting MAXRECURSION 0 on a query with a cycle gives you a query that never ends, so use it only when your termination condition is sound.
MySQL: 1000 levels by default
MySQL limits recursion with the system variable cte_max_recursion_depth, which defaults to 1000. When a query exceeds it, MySQL raises an error and the statement fails. You can raise it for the session:
SET SESSION cte_max_recursion_depth = 5000;
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n WHERE i < 3000
)
SELECT COUNT(*) AS total FROM n;MySQL also has max_execution_time (for SELECT statements, in milliseconds) and a per-statement optimizer hint, /*+ SET_VAR(cte_max_recursion_depth = 5000) */, which changes the limit for one query only.
PostgreSQL and SQLite: no depth limit
Neither engine counts recursion levels. A runaway query keeps running until you cancel it or it exhausts memory or disk. This makes your own termination logic more important here.
In PostgreSQL, set a statement timeout while you develop:
SET statement_timeout = '5s';In SQLite, the usual guard is a LIMIT on the outer query or inside the CTE. SQLite stops generating rows once the limit is reached, because it evaluates the recursion lazily as a queue.
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n
)
SELECT i FROM n LIMIT 10;This query has no WHERE condition in the recursive member, yet it finishes. That works in SQLite, and PostgreSQL also stops early in this simple case. Do not rely on it as your only protection. A LIMIT placed on the outer query does not stop recursion when the query also uses ORDER BY, GROUP BY, or DISTINCT, because those need every row first.
Type matching between anchor and recursive member
The column types of the result come from the anchor member. Problems appear when the recursive member produces a wider value.
In SQL Server, the types and lengths must match exactly between the anchor and the recursive member. This query fails because the anchor creates a varchar(1) column and the recursive member makes a longer string:
WITH s AS (
SELECT 'a' AS txt
UNION ALL
SELECT txt + 'a' FROM s WHERE LEN(txt) < 5
)
SELECT txt FROM s;The fix is to cast the anchor to the width you need:
WITH s AS (
SELECT CAST('a' AS varchar(10)) AS txt
UNION ALL
SELECT CAST(txt + 'a' AS varchar(10)) FROM s WHERE LEN(txt) < 5
)
SELECT txt FROM s;MySQL has a similar trap. It takes the column type from the anchor and, in strict SQL mode, raises an error when the recursive member produces a value that does not fit. A string anchor such as 'a' gives a one-character column. PostgreSQL also needs compatible types and reports an error when the anchor and recursive member disagree, such as integer versus numeric. SQLite is dynamically typed and is the most forgiving.
Building paths
Each engine builds a path in a different way.
PostgreSQL uses arrays, which also make cycle checks easy:
WITH RECURSIVE reach AS (
SELECT src, dst, ARRAY[src, dst] AS path
FROM edges
WHERE src = 1
UNION ALL
SELECT r.src, e.dst, r.path || e.dst
FROM reach r
JOIN edges e ON e.src = r.dst
WHERE e.dst <> ALL (r.path)
)
SELECT dst, path FROM reach;MySQL, SQLite, and SQL Server have no array type, so you build a delimited string and test it with a string function.
-- SQLite: string concatenation uses ||
WITH RECURSIVE reach(dst, path) AS (
SELECT dst, ',' || src || ',' || dst || ','
FROM edges
WHERE src = 1
UNION ALL
SELECT e.dst, r.path || e.dst || ','
FROM reach r
JOIN edges e ON e.src = r.dst
WHERE instr(r.path, ',' || e.dst || ',') = 0
)
SELECT dst, path FROM reach;The commas on both sides of each id matter. Without them, searching for node 1 would match inside 11 and wrongly block a valid step. The same idea works in MySQL with CONCAT(...) and LOCATE(...), and in SQL Server with + (or CONCAT) and CHARINDEX(...). Remember the type-width rule for SQL Server and MySQL: the path column must be wide enough for the longest path, or the query fails.
UNION versus UNION ALL
PostgreSQL, MySQL, and SQLite accept both UNION ALL and UNION between the anchor and the recursive member. UNION removes duplicate rows, so a row already seen is not added again. That can end a cycle on its own when the rows carry no changing column such as depth.
SQL Server accepts only UNION ALL in a recursive CTE. To drop revisits there, you must track visited nodes with a path string, as shown above.
Built-in cycle and ordering clauses (PostgreSQL 14+)
PostgreSQL 14 added SEARCH and CYCLE clauses from the SQL standard. They replace hand-written path arrays for the common cases.
WITH RECURSIVE reach AS (
SELECT src, dst
FROM edges
WHERE src = 1
UNION ALL
SELECT r.src, e.dst
FROM reach r
JOIN edges e ON e.src = r.dst
)
CYCLE dst SET is_cycle USING path
SELECT dst, is_cycle, path FROM reach WHERE NOT is_cycle;CYCLE dst tracks the values of dst. When a row repeats a value already on its path, the engine sets is_cycle to true and stops expanding that row. The path column is generated for you. The SEARCH DEPTH FIRST BY ... SET ... and SEARCH BREADTH FIRST BY ... SET ... clauses add an ordering column so you can sort results depth-first or breadth-first. MySQL, SQLite, and SQL Server do not support these clauses.
Other differences worth knowing
- Column list. PostgreSQL, MySQL, SQLite, and SQL Server all accept
name(col1, col2) AS (...). In SQL Server the list is optional when the anchor gives every column a name. - Restrictions on the recursive member. SQL Server forbids
TOP,DISTINCT,GROUP BY,HAVING, aggregate functions, and outer joins that put the CTE on the nullable side. PostgreSQL and MySQL are stricter about aggregates and subqueries that refer to the CTE, but allow more than SQL Server. The CTE name may appear only once in the recursive member in MySQL and in most engines. - Older versions. MySQL before 8.0 and MariaDB before 10.2.2 have no recursive CTEs. SQLite supports them from version 3.8.3. If you run on one of these, check the version first.
- Materialization. MySQL and SQLite store recursive results in a temporary table. Very large results can spill to disk, so check
tmp_table_sizeandmax_heap_table_sizein MySQL.
Porting checklist
- Add or remove
RECURSIVEto match the target engine. - Replace array logic with delimited strings, or the reverse.
- Replace
||with+orCONCATfor SQL Server and MySQL. - Cast anchor columns to the widest type the recursive member will produce.
- Add
OPTION (MAXRECURSION n)for SQL Server, or raisecte_max_recursion_depthfor MySQL, if your depth can exceed the default. - Add a termination condition or a cycle guard that does not depend on an engine limit.
Exercise
You run a recursive CTE that counts from 1 to 500 on SQL Server and get error 530 about the maximum recursion being exhausted. Which change fixes it, and why would the same query not fail on PostgreSQL?
Show answer
Add OPTION (MAXRECURSION 500) (or a larger value) at the end of the outer SELECT. SQL Server stops at 100 recursion levels by default, and counting to 500 needs 499 levels. PostgreSQL has no default depth limit, so the query finishes as long as the WHERE i < 500 condition ends the recursion.
Exercise
A query that builds a path string such as '1,2,11' checks for revisits with a search for the node id as plain text. It wrongly skips node 1 after it has visited node 11. What is the bug, and what is the fix?
Show answer
The text search for '1' matches inside '11'. Wrap every id in delimiters, store the path as ',1,2,11,', and search for ',' || id || ',' (or the equivalent CONCAT or + form), so only whole ids match.