public inbox for [email protected]  
help / color / mirror / Atom feed
From: [email protected]
To: [email protected]
Subject: Abitity to identify the current iteration in a recursive SELECT (feature request)
Date: Mon, 16 Dec 2024 12:21:03 +0200
Message-ID: <CAGH1kmyB7D7+xj4=HkEPPNoK1irm4OdgOMZe-GDqFWsLAa9m-A@mail.gmail.com> (raw)

Hi,

the algorithm present here
<https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-RECURSIVE;
for the resolution of WITH RECURSIVE queries is, broadly speaking,
iterative, with the iteration sequence number indicated in the first row
item of the field generated by the SEARCH BREADTH FIRST clause, i.e. *0*,
*1*, *2* etc.

Is there a way to obtain directly this iteration sequence number within the
SELECT statement following the UNION keyword in a recursive construction? I
know it can by obtained by maintaining its value in a working table column,
but that's suboptimal - I need it as a "magic" variable, akin, for example,
the excluded variable available inside the ON CONFLICT DO UPDATE clause of
an INSERT statement.

*Background*
I'm using the a recursive SELECT in order to join iteratively several
(virtual) tables computed dinamically based on the iteration number. Why?
In order to implement a set intersection, with each set extracted from a
jsonb column of a table.
If the iteration number was a distinct column of the working table, the
table joined in each iteration would need use LATERAL, thus building it for
as many times as the number of rows in the working table instead of *just
once*.

*Workaround*
I simulated the said missing variable with a sequence, which is cumbersome
because;

   - the sequence is single-use, so it must be named randomly, created
   before and dropped after the WITH RECURSIVE ... SELECT statement;
   - nextval('sequence_name') *cannot* be used directly within WHERE
   clauses, because it is re-evaluated for each row; the next sequence value
   must be reached through a phrase like join (select
   nextval('sequence_name')) in order to ensure a single evaluation per
   iteration.


reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected]
  Subject: Re: Abitity to identify the current iteration in a recursive SELECT (feature request)
  In-Reply-To: <CAGH1kmyB7D7+xj4=HkEPPNoK1irm4OdgOMZe-GDqFWsLAa9m-A@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox