Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
The simplest recursive CTE#
I found this really simple recursive CTE useful for ensuring I understood how to write recursive CTEs.
1with recursive counter(x) as (2 select 03 union4 select x + 1 from counter5)6select * 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:
1with recursive counter as (2 select 0 as x3 union4 select x + 1 from counter5)6select * 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:
1with recursive counter(x, y) as (2 select 0 as x, 1 as y3 union4 select x + 1, y + 2 from counter5)6select * from counter limit 5;| x | y |
|---|---|
| 0 | 1 |
| 1 | 3 |
| 2 | 5 |
| 3 | 7 |
| 4 | 9 |
Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.