Re: Guidance on INSERT RETURNING order

From: Federico <cfederico87(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>, John Howroyd <jdhowroyd(at)googlemail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Guidance on INSERT RETURNING order
Date: 2023-04-15 06:54:36
Message-ID: CAN19dyfYSEMUt+f_TCJ-aQ1+_RNYVbnpQyRD9wwzYfFTWwDORQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sat, 15 Apr 2023 at 05:17, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:
>
> Federico <cfederico87(at)gmail(dot)com> writes:
> > Would something like what was proposed by Mike Bayer be considered?
>
> >> A new token called "tuple_order" or something
> >>
> >> INSERT INTO table (a, b, c) VALUES ((1, 2, 3), (4, 5, 6), ...) RETURNING table.id, inserted.tuple_order
> >>
> >> tuple_order would be incrementing values 1, 2, 3, 4, 5, ... which correlate the each row delivered by RETURNING to each entry in the VALUES clause, in the order they were stated in that VALUES clause, that is entry (1, 2, 3) would be tuple_order 1, entry (4, 5, 6) would be tuple order 2, etc.
>
> As proposed, I don't think so. Something over in the RETURNING clause has
> exactly no connection to VALUES. What do you do if it's INSERT ... SELECT
> and there are several VALUES clauses down inside the SELECT?

I think the tuple order would not be connected to the values, but be
determined by the input order of the rows in the insert. So when using
INSERT ... SELECT the tuple_order value would be determined by the
output of the select, using the same logic as ROW_NUMBER.

> There is some prior art in this area, though. See the more-or-less
> SQL-standard WITH ORDINALITY option for functions-in-FROM. It seems to me
> that it could be plausible to attach WITH ORDINALITY to a VALUES clause,
> which would give you a rock-solid connection between the VALUES rows and
> the ordinality-column values, and then you could include that column in
> RETURNING.

Well if returning could output rows that are not in the inserted
table, like mentioned also by Devid Johnston, it would open to
alternatives to tuple_order, like using

INSERT INTO tbl(data)
SELECT v.d FROM (VALUES ('x', 1), ('y', 2)) AS v(d, num)
RETURNING tbl.id, v.num

> regards, tom lane

I'm not familiar with the internals of Postgresql, so I don't know
what would be more complex to implement in this case. I think both
solutions would work equally well from the client point of view.

Thanks for the reply,
Federico

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alexander Farber 2023-04-15 10:06:21 Should I add a new schema for my application?
Previous Message David G. Johnston 2023-04-15 03:39:56 Re: Guidance on INSERT RETURNING order