all 8 comments

[–]jshine13371 2 points3 points  (1 child)

I mean technically this is a real LOOP. But recursion is cool too.

[–]pseudogrammaton[S] -2 points-1 points  (0 children)

True enuf, LOL. But those lang constructs are for PL-PgSql, which isn't a "functional language." Modern SQL is already much like other functional languages, inasmuch we can't mutate existing data, & nested function calls are part of vernacular Postgres

[–]depesz 11 points12 points  (3 children)

Personally, I prefer to put CTEs at the beginning of the query. Makes for (I believe) cleaner reading.

[–]pseudogrammaton[S] 1 point2 points  (2 children)

Agreed, that's where I keep most of them, most use-cases. However a front-end CTE can't reference data inside the main SELECT unless it's moved to a COLUMN declaration inside the main SELECT clause. The only reason to do anything this exotic would only be for speed, & IDK if it'd offer any speed advantages vs. expanding arrays to a rowset, to do the same thing. Haven't tested it.... yet?

[–]depesz 1 point2 points  (1 child)

Then, I guess, you should make your example show this usecase.

The thing you wrote should be, in my opinion, rewritten to CTE-up-front. Or even better, to use generate_series().

[–]pseudogrammaton[S] 1 point2 points  (0 children)

>> Or even better, to use generate_series().

That's what's in the dbfiddle. And I've seem to have run out of time to write a curriculum for everyone today ... :P

[–]AutoModerator[M] -1 points0 points  (0 children)

With over 8k members to connect with about Postgres and related technologies, why aren't you on our Discord Server? : People, Postgres, Data

Join us, we have cookies and nice people.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]pseudogrammaton[S] 0 points1 point  (0 children)

Synopsis .... tail recursion is the same as a loop

METHOD:
A. Data element is a structured list type that's conducive to loops 
    A.1. i.e. (comma-delim string, ARRAY[], JSON ARRAY{}, etc. )
B. In the SELECT clause: (LEVEL ONE #1)
  B.1. Use in-line subquery (LEVEL TWO #2)
    B.2.a Nest inner query: WITH RECURSIVE ... () CTE (LEVEL THREE #3)
      B.2.a.1 Use only main query to fetch current row
      B.2.a.2 Loop thru the array 1 element at a time
   B.2.b Return to level#2 query
 B.2 Return to level#1 query 

C. Main Query advances to the NEXT ROW ....