Save return values from INSERT...RETURNING into temp table (PostgreSQL) Save return values from INSERT...RETURNING into temp table (PostgreSQL) postgresql postgresql

Save return values from INSERT...RETURNING into temp table (PostgreSQL)


with inserted as (  INSERT INTO table1 (value1,value2)   SELECT value3,value4   FROM table2   RETURNING id) insert into tempselect id from inserted;

This requires Postgres 9.2 or later.


Two options.

If you need it just for one follow-up query, a with statement (see the horse's answer) is the easiest.

If you need it for more than one follow-up query, the other option is to not use insert ... returning, but rather create table as:

CREATE TEMPORARY TABLE foo ASSELECT value3,value4 FROM table2

Caveats: if necessary, create the indexes you need on the table -- and analyze it if you do.