0

I'm trying to insert a row into a table named table1 if only 'value' exists in table2. The newly created row returns an id and I want to use this id through a WITH query and insert it into a third table named table3.

Here is the sql statement I used.

WITH new_key AS (
    INSERT INTO table1(name, value) 
    SELECT 'test', value
        FROM table2 
    WHERE value = 'some_value'
    RETURNING id
)
INSERT INTO table3(table1_id) 
VALUES (new_key);

The INSERT query in the WITH query works and returns an id. Unfortunately the whole statement returns "new_key column does not exist".

2
  • an INSERT don't return "values" .. you need a insert ..select Commented Apr 21, 2019 at 19:01
  • That's exactly what I did not understand. Thank you. Commented Apr 21, 2019 at 19:06

1 Answer 1

1

You need to select the value from the CTE:

WITH new_key AS (
    INSERT INTO table1(name, value) 
    SELECT 'test', value
        FROM table2 
    WHERE value = 'some_value'
    RETURNING id
)
INSERT INTO table3(table1_id) 
SELECT id
FROM new_key;
Sign up to request clarification or add additional context in comments.

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.