Re: Unable to use INSERT ... RETURNING with column from other table

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Andreas Joseph Krogh <andreas(at)visena(dot)com>
Cc: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Unable to use INSERT ... RETURNING with column from other table
Date: 2017-10-25 01:56:02
Message-ID: CAKFQuwZ8O8QVU8YvF6BnDD4yFxK_EgvBEuAGyoyCOyQO+N+O0g@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Tuesday, October 24, 2017, Andreas Joseph Krogh <andreas(at)visena(dot)com>
wrote:
>
> WITH upd_h(new_header_id, header_name, old_header_id) AS (
> INSERT INTO tbl_header(id, name)
> SELECT 3, h.name
> FROM tbl_header h WHERE h.id = 1 RETURNING id, name, 1 -- need h.id here)
> INSERT INTO tbl_value(header_id, name)SELECT f.new_header_id, hv.nameFROM tbl_value hv
> JOIN tbl_header h ON hv.header_id = h.id
> JOIN upd_h AS f ON hv.header_id = f.old_header_id
> ;
>
>
> This fails with:
> ERROR: missing FROM-clause entry for table "h"
> LINE 5: RETURNING id, name, h.id
>
>
> Is what I'm trying to do possible? I'd like to avoid having to use
> temp-tables and/or PLPgSQL for this as I need to insert many such values in
> large batches...
>
>

Not directly that I know of. Options:

1. Updatable view.

2. In this particular example you can place the desired h.id in its own
CTE. Move the insert into a CTE. Then join the insert-returning CTE with
the input CTE.

WITH input AS ( 1 as hid ),
ins1 as ( insert select where h.id = (select hid from input) returning *)
Select * from ins1 cross join input

David J.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Peter Geoghegan 2017-10-25 02:45:13 Re: Unable to use INSERT ... RETURNING with column from other table
Previous Message Andreas Joseph Krogh 2017-10-25 00:21:19 Re: Unable to use INSERT ... RETURNING with column from other table