PostgreSql INSERT FROM SELECT RETURNING ID

SqlPostgresqlInsertPostgresql 9.2

Sql Problem Overview


In PostgreSql 9.2.4 I have two tables: user (id, login, password, name) and dealer (id, user_id).

And I want to insert into both tables returning id of created dealer.

Currently I'm doing it with two queries:

WITH rows AS (
    INSERT INTO "user"
	    (login, password, name)
    VALUES
	    ('dealer1', 'jygbjybk', 'Dealer 1')
    RETURNING id
)
INSERT INTO dealer (user_id)
    SELECT id
    FROM rows;
SELECT currval('dealer_id_seq');

But can I implement this with a single INSERT query using RETURNING statement?

Sql Solutions


Solution 1 - Sql

You just need to add a RETURNING id to your INSERT ... SELECT:

WITH rows AS (...)
INSERT INTO dealer (user_id)
    SELECT id
    FROM rows
    RETURNING id;

Demo: http://sqlfiddle.com/#!12/75008/1

Solution 2 - Sql

For my purposes, I needed it in a variable so I did this:

INSERT INTO dealer (user_id)
    SELECT id
    FROM rows
    RETURNING id INTO l_dealerid;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNailgunView Question on Stackoverflow
Solution 1 - Sqlmu is too shortView Answer on Stackoverflow
Solution 2 - SqlBlair KjennerView Answer on Stackoverflow