Is "WITH RECURSIVE" limited to the first position of CTEs by design?

Started by Kirk Wolakover 2 years ago3 messagesgeneral
Jump to latest
#1Kirk Wolak
wolakk@gmail.com

Team,
This was strange. I wanted to set up a CTE that would FEED my recursive
query.
And also feed the results filtering...

These are the most trivial examples. The second one results in a syntax
error. Which implies that:
1) There can only be one recursive CTE at the same level?
2) It must be the FIRST CTE?

Example:
WITH RECURSIVE CTE1 AS (select 2 UNION ALL SELECT 0),
CTE2 AS (select 1 UNION ALL SELECT 0) select 3 ;

-- This does not work:

WITH CTE1 AS (select 2 UNION ALL SELECT 0),
RECURSIVE CTE2 AS (select 1 UNION ALL SELECT 0)
SELECT 3;
--> ERROR: syntax error at or near "CTE2"

Thanks in advance...

Kirk

#2David G. Johnston
david.g.johnston@gmail.com
In reply to: Kirk Wolak (#1)
Re: Is "WITH RECURSIVE" limited to the first position of CTEs by design?

On Mon, Nov 13, 2023 at 9:17 AM Kirk Wolak <wolakk@gmail.com> wrote:

These are the most trivial examples. The second one results in a syntax
error. Which implies that:
1) There can only be one recursive CTE at the same level?
2) It must be the FIRST CTE?

There is only one WITH keyword as well, that doesn't change the fact there
can be multiple attached queries to it.

The documentation explains clearly the implications on adding the keyword
RECURSIVE after the keyword WITH.

https://www.postgresql.org/docs/current/sql-select.html#SQL-WITH

David J.

#3Tom Lane
tgl@sss.pgh.pa.us
In reply to: David G. Johnston (#2)
Re: Is "WITH RECURSIVE" limited to the first position of CTEs by design?

"David G. Johnston" <david.g.johnston@gmail.com> writes:

On Mon, Nov 13, 2023 at 9:17 AM Kirk Wolak <wolakk@gmail.com> wrote:

These are the most trivial examples. The second one results in a syntax
error. Which implies that:
1) There can only be one recursive CTE at the same level?
2) It must be the FIRST CTE?

There is only one WITH keyword as well, that doesn't change the fact there
can be multiple attached queries to it.

Yeah, RECURSIVE is attached to the WITH not to the query. That's
because it has global implications for the visibility of the CTE
names across all the CTEs in the WITH.

regards, tom lane