Document ordering guarantees on INSERT/UPDATE RETURNING clause - Mailing list pgsql-hackers

From Shay Rojansky
Subject Document ordering guarantees on INSERT/UPDATE RETURNING clause
Date
Msg-id CADT4RqCvuRucgqZjKJypsjAPeEg3QBDND4z1JW4mX=X9fWFkpg@mail.gmail.com
Whole thread Raw
Responses Re: Document ordering guarantees on INSERT/UPDATE RETURNING clause  ("David G. Johnston" <david.g.johnston@gmail.com>)
List pgsql-hackers
Hi all,

I've seen various discussions around whether PG makes any guarantees on the ordering of rows returned by the RETURNING clause (e.g. [1]). In a nutshell, when executing a statement such as the following:

CREATE TABLE foo (id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, data INT);
INSERT INTO foo (data) VALUES (8), (9), (10) RETURNING id, data;

... us the INSERT guaranteed to return the rows (1,8), (2,9) and (3,10) (and in that order)? This point is important when inserting multiple rows and wanting to e.g. match a database-generated ID back to memory structures on the client.

FWIW I've received feedback from a SQL Server engineer that one definitely should *not* depend on such ordering there, and that future optimizations (e.g. parallel insertion of many rows) could result in row ordering which differs from the lexical ordering of the VALUES clause. That seems very reasonable; if the situation is similar on PostgreSQL, then I'd suggest making that very clear in the INSERT[2] and UPDATE[3] docs. I'd also possibly point to the workaround of wrapping the INSERT/UPDATE in a CTE which then defines the ordering.

Thanks,

Shay

pgsql-hackers by date:

Previous
From: Bharath Rupireddy
Date:
Subject: Re: Allow async standbys wait for sync replication (was: Disallow quorum uncommitted (with synchronous standbys) txns in logical replication subscribers)
Next
From: "David G. Johnston"
Date:
Subject: Re: Document ordering guarantees on INSERT/UPDATE RETURNING clause