Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1ZXTd6-0002E3-7B for pgsql-bugs@arkaria.postgresql.org; Thu, 03 Sep 2015 12:28:36 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84) (envelope-from ) id 1ZXTd5-0008Sb-LV for pgsql-bugs@arkaria.postgresql.org; Thu, 03 Sep 2015 12:28:35 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84) (envelope-from ) id 1ZXTcT-0007lK-Q8 for pgsql-bugs@postgresql.org; Thu, 03 Sep 2015 12:27:57 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84) (envelope-from ) id 1ZXTcN-00033D-Pb for pgsql-bugs@postgresql.org; Thu, 03 Sep 2015 12:27:56 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id t83CRn4B010915; Thu, 3 Sep 2015 08:27:49 -0400 From: Tom Lane To: Sjon Hortensius cc: pgsql-bugs@postgresql.org Subject: Re: INSERT INTO .. SELECT nextval() ORDER BY - returns unexpectedly ordered values In-reply-to: References: Comments: In-reply-to Sjon Hortensius message dated "Thu, 03 Sep 2015 14:05:21 +0200" Date: Thu, 03 Sep 2015 08:27:49 -0400 Message-ID: <10914.1441283269@sss.pgh.pa.us> X-Pg-Spam-Score: -1.9 (-) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-bugs Precedence: bulk Sender: pgsql-bugs-owner@postgresql.org Sjon Hortensius writes: > INSERT INTO test2 SELECT name, nextval('tmp'), id FROM test ORDER BY id ASC; > I have worked around this by clustering the old table on the new id before > SELECTing but this behavior doesn't seem to be documented, is this a bug? No. You're assuming that the nextval() happens after the row ordering, but this is not necessarily so --- indeed, a strict reading of the SQL standard would imply that it should *never* be so, because the standard execution model is that ORDER BY happens after computing the SELECT list. (Without that, locutions like "ORDER BY 1" would make no sense.) It might accidentally work if the ORDER BY were done via an indexscan rather than an explicit sort step, but that's not possible in your test case. Try something like this to force the evaluation order: INSERT INTO test2 SELECT name, nextval('tmp'), id FROM (SELECT name, id FROM test ORDER BY id ASC) ss; regards, tom lane -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs