Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

postgresql - Is INSERT RETURNING guaranteed to return things in the "right" order?

Example:

create table foo(
    id serial, 
    txt text
);

insert into foo(txt) values ('a'),('b'),('c') returning id;

Returns:

 id 
----
  1
  2
  3
(3 rows)

It seems that the first id in the return value will always be the id for 'a', the second for 'b' and so on, but is this defined behaviour of insert into, or is it a coincidence that may fail under odd circumstances?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't see anything in the documentation that guarantees an order for RETURNING so I don't think you can depend on it. Odds are that the RETURNING order will match the VALUES order but I don't see any guarantees about what order the VALUES will be inserted in either; the VALUES are almost certainly going to be insert in order from left to right but again, there is no documented guarantee.

Also, the relational model is set based so ordering is something applied by the user rather than an inherent property of a relation. In general, if there is no way to explicitly specify an ordering, there is no implied ordering.

Execute summary: the ordering you're seeing is probably what will always happen but it is not guaranteed so don't depend on it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...