Sub topic 8
WITH RECURSIVE versus WITH: Differences Across Databases
This chapter assumes you know SELECT, JOIN, WHERE, GROUP BY, and basic subqueries. You should also understand that a common table expression (CTE) exists only for the statement that contains its WITH clause.
The keyword difference
A recursive CTE refers to itself. Many database systems require you to announce this with RECURSIVE:
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 5
)
SELECT n
FROM numbers;The first SELECT is the anchor member. It creates the starting row. The second SELECT is the recursive member. It reads from numbers and creates the next row. UNION ALL combines the rows from both members.
PostgreSQL, MySQL 8 and later, and SQLite use this form:
WITH RECURSIVE ...SQL Server uses WITH without RECURSIVE:
WITH numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 5
)
SELECT n
FROM numbers
OPTION (MAXRECURSION 100);In SQL Server, OPTION (MAXRECURSION n) controls the maximum number of recursive iterations. The default limit is 100. OPTION (MAXRECURSION 0) removes that limit, but use it only when you have another reliable termination condition.
Oracle also uses WITH without the RECURSIVE keyword, but its recursive subquery factoring syntax and rules differ from SQL Server. Oracle also provides CONNECT BY, an older hierarchical-query feature that may be more natural for organization charts and trees in Oracle-specific code.
Portability differences
The recursive idea is portable, but the exact statement may not be. Check these details before moving a query between systems.
| Concern | PostgreSQL, MySQL, SQLite | SQL Server | Oracle |
|---|---|---|---|
| Recursive keyword | `WITH RECURSIVE` | `WITH` | `WITH` |
| Recursion limit | Engine-specific behavior | 100 by default | Engine-specific |
| Date functions | Differ by dialect | Differ by dialect | Differ by dialect |
| Hierarchy feature | Recursive CTE | Recursive CTE | Recursive CTE or `CONNECT BY` |
Statement termination
SQL Server requires a semicolon before a WITH clause if another statement comes immediately before it:
;WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total
FROM order_totals;Writing the leading semicolon is also valid in many other systems, so it can make shared scripts safer. It does not solve differences in recursive syntax or functions.
Column names and types
A recursive CTE usually has an explicit column list:
WITH RECURSIVE org(id, name, manager_id, depth) AS (
SELECT id, name, manager_id, 0
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1
FROM employees AS e
JOIN org AS o ON e.manager_id = o.id
)
SELECT id, name, depth
FROM org;The anchor and recursive members must return the same number of columns. Corresponding columns must also have compatible data types. Some systems infer a type that is too narrow from the anchor member. An explicit cast can prevent errors:
WITH RECURSIVE paths(id, path) AS (
SELECT id, CAST(name AS VARCHAR(1000))
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, p.path || ' / ' || c.name
FROM categories AS c
JOIN paths AS p ON c.parent_id = p.id
)
SELECT id, path
FROM paths;The string concatenation operator in this example is PostgreSQL and SQLite style. MySQL commonly uses CONCAT, and SQL Server uses +. This is one reason a logically portable CTE may still need dialect-specific expressions.
Execution and performance
A CTE is a query expression, not automatically a permanent table. An engine may materialize it, meaning it computes and stores its rows temporarily, or inline it, meaning it merges the expression into the surrounding query plan.
PostgreSQL can often inline a nonrecursive CTE. You can request a specific behavior in supported PostgreSQL versions:
WITH recent AS MATERIALIZED (
SELECT *
FROM orders
WHERE order_date >= DATE '2026-01-01'
)
SELECT COUNT(*)
FROM recent;MATERIALIZED can help when several parts of a query reuse an expensive result. It can hurt when storing the intermediate rows prevents useful filter or join optimization. Other databases use different rules and do not support these keywords.
Recursive CTEs generally need repeated work, so index the columns used to find the next level, such as employees.manager_id or categories.parent_id. Always include a condition that makes recursion stop.
Choosing portable syntax
Use a nonrecursive WITH when you only need to name intermediate results. Use a recursive CTE when each level depends on rows found at the previous level. For code that must run on several databases:
- Keep the anchor and recursive members structurally simple.
- Add the database-specific keyword or recursion option in an adapter layer.
- Avoid relying on undocumented row order.
- Replace date, string, and concatenation functions for each dialect.
- Test empty roots, missing parents, deep trees, and cycles.
- Inspect execution plans separately on each database.
Exercise
You need to run a recursive sequence query on PostgreSQL and SQL Server. What must change, and what should remain the same?
Show answer
PostgreSQL needs WITH RECURSIVE, while SQL Server uses WITH and can add OPTION (MAXRECURSION 100). The CTE column list, anchor member, recursive member, UNION ALL, and termination condition can remain conceptually the same.