Re: Semantics around INSERT INTO with SELECT and ORDER BY.

From: Steve Krenzel <sgk284(at)gmail(dot)com>
To: tgl(at)sss(dot)pgh(dot)pa(dot)us
Cc: david(dot)g(dot)johnston(at)gmail(dot)com, Ravi Krishna <sravikrishna3(at)gmail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Semantics around INSERT INTO with SELECT and ORDER BY.
Date: 2018-06-12 16:37:12
Message-ID: CADBwkHsnBSmXnaL3ousLX9RxXko3k29K1nt4+Aq1UG54iLfwaA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Thank you all! Your answers cleared this up for me.

Tom, in particular, that reference commit removed any ambiguity for me.
Thank you. It's much appreciated.

On Tue, Jun 12, 2018 at 7:27 AM Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:

> "David G. Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com> writes:
> > On Tuesday, June 12, 2018, Steve Krenzel <sgk284(at)gmail(dot)com> wrote:
> >> This is relevant for tables that have a column with a SERIAL type, I
> need
> >> to guarantee that the relative ordering remains the same as the
> ordering of
> >> the selected result set.
>
> > The logical insertion order, and thus the sequence values, will be
> assigned
> > according to the order by.
>
> What is actually going to happen, given say
>
> create table targ (d text, id serial);
>
> insert into targ select x from src order by y;
>
> is that you're going to get a parse tree equivalent to
>
> select x, nextval('targ_id_seq')
> from (select x from src order by y) ss;
>
> and then it's a question of whether the planner is capable of reordering
> the steps into something you don't want. I think that the presence of
> the explicit "ORDER BY" in the sub-select will prevent flattening of the
> sub-select, which is enough to make it safe. However, if for some reason
> you did not say "ORDER BY" but nonetheless expected the serial values to
> get assigned in the same order that the underlying query would produce
> rows natively, you might get burnt.
>
> As of 9.6, there are more guarantees in this area than there used
> to be (cf commit 9118d03a8), but I don't think it matters as long
> as you write an ORDER BY.
>
> regards, tom lane
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2018-06-12 17:10:28 Re: PG on AWS RDS and IAM authentication
Previous Message Scott Stroupe 2018-06-12 16:31:49 Print pg_lsn as a number?