3

This query generates the numbers from 1 to 4.

with recursive z(q) as (
  select 1
  union all
  select q + 1 from z where q < 4
  )
select * from z;

But, if I modify it to this,

with x as (
  select 1 y
  ),
recursive z(q) as (
  select y from x
  union all
  select q + 1 from z where q < 4
  )
select * from z;

It gives

ERROR: syntax error at or near "z"

What did i do wrong here?

Noel
  • 10,152
  • 30
  • 45
  • 67

1 Answers1

4

I think this is because RECURSIVE is modifier of WITH statement, not a property of common table expression z, so you can use it like this:

with recursive
x as (
  select 1 y
),
z(q) as (
  select y from x
  union all
  select q + 1 from z where q < 4
)
select * from z;

sql fiddle demo

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • 1
    Recursive enables self-referencing queries in any of the list of multiple CTEs, not just the first. – wistlo Mar 19 '22 at 23:32