10

I have a table table1 with columns id,value1 and value2.

Also I have a query

INSERT INTO table1(value1,value2) SELECT value3,value4 FROM table2 RETURNING id

that returns set of ids. I want to store return values (these ids) in some temp table. Something like that:

INSERT INTO TEMP temp1 INSERT INTO table1(value1,value2) SELECT value3,value4 FROM table2 RETURNING id

How can I do it?

DBMS is PostgreSQL

2 Answers 2

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

This requires Postgres 9.2 or later.

Sign up to request clarification or add additional context in comments.

1 Comment

for future readers : this is : "Common Table Expressions" aka "CTE"s see -> postgresql.org/docs/current/queries-with.html
5

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 AS
SELECT value3,value4 FROM table2

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

1 Comment

for future readers : "a with statement" : postgresql.org/docs/current/queries-with.html "Common Table Expressions" aka "CTE"s is the other name for it. upvote for the 2 reasons given here for "one time" or "later re-use"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.