1

So I'm trying to insert a value into a secondary table, get the returned id from the insert, and use it together with some values in a prepared statement I'm writing.The return of the first statement(table2) is an id for a foreign key column in the first table. I want to get the id of table 1 in the end.Something like :

WITH table2ID AS
(
INSERT INTO table2 (value) VALUES ('somevalue') RETURNING id;
)
INSERT INTO table1(table2returnvalue,othervalue) VALUES
(table2ID 'val2') RETURNING id

I can see that I will probably need a transaction as well, because I don't want an isolated in table2 if table1's statement fails for some reason.

Could you please help?

2
  • What exactly is your question? A single statement (and that's what you have) is always atomic. It either succeeds completely or fails completely. Commented Feb 17, 2015 at 17:18
  • As I specified I'm trying to use the return value from an earlier insert as a value for the next insert statement Commented Feb 17, 2015 at 17:35

2 Answers 2

2

To do this with a CTE its usually easiest to return the entire row (output from table2) and reference that in your second insert query.

WITH table2 AS
(
    INSERT INTO table2 ( value )
    VALUES ( 'somevalue' )
    RETURNING table2.*;
)
INSERT INTO table1 ( table2returnvalue, othervalue )
SELECT table2.id, 'val2'
FROM table2
RETURNING table1.id
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this was a great help!
1

I think you're looking for something like this:

WITH table2ID AS
(
  INSERT INTO table2 (value) VALUES ('somevalue') RETURNING id;
)
INSERT INTO table1(table2returnvalue,othervalue) 
SELECT table2ID.id, 'val2' FROM table2ID;

Comments

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.