Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1e7C12-0003dw-Sa for pgsql-sql@arkaria.postgresql.org; Wed, 25 Oct 2017 03:06:00 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1e7C11-00055s-Ti for pgsql-sql@arkaria.postgresql.org; Wed, 25 Oct 2017 03:05:59 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1e7Bzz-0003EC-5U for pgsql-sql@postgresql.org; Wed, 25 Oct 2017 03:04:55 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1e7Bzs-0002s3-0X for pgsql-sql@postgresql.org; Wed, 25 Oct 2017 03:04:54 +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 v9P34iOC015481; Tue, 24 Oct 2017 23:04:44 -0400 From: Tom Lane To: Peter Geoghegan cc: Andreas Joseph Krogh , pgsql-sql@postgresql.org Subject: Re: Unable to use INSERT ... RETURNING with column from other table In-reply-to: References: Comments: In-reply-to Peter Geoghegan message dated "Tue, 24 Oct 2017 19:45:13 -0700" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <15479.1508900684.1@sss.pgh.pa.us> Date: Tue, 24 Oct 2017 23:04:44 -0400 Message-ID: <15480.1508900684@sss.pgh.pa.us> List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-sql Precedence: bulk Sender: pgsql-sql-owner@postgresql.org Peter Geoghegan writes: > As David says, you could use multiple CTEs for this. Yeah. The SELECT portion of the query, so far as the outer INSERT is concerned, is just a black box that yields some column values to be inserted. We could wish that the INSERT's RETURNING clause could examine additional column values that are available inside that subquery, but I'm afraid that there are insurmountable semantic problems. In particular, DISTINCT seems to break that entirely --- consider insert into foo(id, name) select distinct 3, f.name from foo f where ... returning id, f.id; We can't just add "f.id" to the set of columns returned by the SELECT part without changing the semantics of the DISTINCT. Or if we ignore that (acting like it was DISTINCT ON (3, f.name)) then we get an underdetermined value of f.id, which doesn't seem appetizing either. regards, tom lane -- Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-sql