Re: Combine non-recursive and recursive CTEs?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Magnus Hagander <magnus(at)hagander(dot)net>
Cc: PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Combine non-recursive and recursive CTEs?
Date: 2012-06-16 06:52:16
Message-ID: 13122.1339829536@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Magnus Hagander <magnus(at)hagander(dot)net> writes:
> Basically, I'd like to combine a recursive and a non-recursive CTE in
> the same query.

Just mark them all as recursive. There's no harm in marking a CTE as
recursive when it isn't really.

> Trying something like:
> WITH t1 (z,b) AS (
> SELECT a,b FROM x
> ),
> RECURSIVE t2(z,b) AS (
> SELECT z,b FROM t1 WHERE b IS NULL
> UNION ALL
> SELECT z,b FROM t2 INNER JOIN t1 ON t2.b=t1.z
> )

> I get a syntax error on the RECURSIVE.

The SQL spec says RECURSIVE can only appear immediately after WITH,
so it necessarily applies to all the CTEs in the WITH list.

The reason why it's like that is that RECURSIVE affects the visibility
rules for which CTEs can refer to which other ones. I think the SQL
committee would have done better to keep the two concepts separate,
but they didn't ...

regards, tom lane

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Fabien COELHO 2012-06-16 07:42:31 Pg default's verbosity?
Previous Message PostgreSQL - Hans-Jürgen Schönig 2012-06-16 06:42:32 Re: Combine non-recursive and recursive CTEs?