SQL error
relation "n" does not exist (a recursive CTE without RECURSIVE)
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
A CTE that refers to itself must be declared WITH RECURSIVE. Without the keyword, PostgreSQL looks for an existing table with that name and doesn't find one.
The exact messages
- PostgreSQLERROR: relation "n" does not exist
- SQLiteNo error, but a silent surprise: see below.
How to read this message
This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot. DETAIL says more about what went wrong. HINT is PostgreSQL's own suggestion, and it's usually worth following.
ERROR: relation "n" does not exist
LINE 4: SELECT x + 1 FROM n WHERE x < 5
^
DETAIL: There is a WITH item named "n", but it cannot be referenced from this part of the query.
HINT: Use WITH RECURSIVE, or re-order the WITH items to remove forward references.Why it happens
RECURSIVE left out
The CTE's second half selects from the CTE itself (FROM n), which only works when it's declared recursive.
A CTE used before it's defined
Non-recursive CTEs can only use the ones written above them. Reorder them, or add RECURSIVE.
Reproduce it, then fix it
Both queries run on a real database in your browser. Switch dialects to compare.
WITH n(x) AS (
SELECT 1
UNION ALL
SELECT x + 1 FROM n WHERE x < 5
)
SELECT x FROM n;WITH RECURSIVE n(x) AS (
SELECT 1
UNION ALL
SELECT x + 1 FROM n WHERE x < 5
)
SELECT x FROM n;One word: RECURSIVE. The query then counts from 1 to 5 in both databases.
The fix returns, PostgreSQL: 5 rows
| x |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
The fix returns, SQLite: 5 rows
| x |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
Experiment with it: PostgreSQL playground·SQLite playground
What SQLite does instead
SQLite treats the RECURSIVE keyword as optional, so the same query runs there. Write it anyway: it's required in PostgreSQL and makes the intent clear.
Official documentation
Stop hitting this error
Practise the concept behind it in a five-minute lesson, or read the full guide: SQL recursive CTEs (WITH RECURSIVE).