161 words
1 minute
The simplest recursive CTE
Anubhav Gain
2024-04-20

The simplest recursive CTE#

I found this really simple recursive CTE useful for ensuring I understood how to write recursive CTEs.

with recursive counter(x) as (
select 0
union
select x + 1 from counter
)
select * from counter limit 5;

This query returns five rows from a single column x - from 0 to 4.

x
0
1
2
3
4

If you write with recursive counter as ..., omitting the (x), you get the following error:

no such column: x

You can fix that by assigning x as the alias in the first part of that union:

with recursive counter as (
select 0 as x
union
select x + 1 from counter
)
select * from counter limit 5;

So that counter(x) formulation is really just a way to define the column names up front.

This query returns two columns, x and y:

with recursive counter(x, y) as (
select 0 as x, 1 as y
union
select x + 1, y + 2 from counter
)
select * from counter limit 5;
xy
01
13
25
37
49
The simplest recursive CTE
https://mranv.pages.dev/posts/the-simplest-recursive-cte/
Author
Anubhav Gain
Published at
2024-04-20
License
CC BY-NC-SA 4.0