Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSql INSERT FROM SELECT RETURNING ID

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?

like image 376
Nailgun Avatar asked Oct 03 '13 19:10

Nailgun


People also ask

What does insert query return in Postgres?

The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON CONFLICT DO UPDATE clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number.

What is returning * Postgres?

A common shorthand is RETURNING * , which selects all columns of the target table in order. In an INSERT , the data available to RETURNING is the row as it was inserted. This is not so useful in trivial inserts, since it would just repeat the data provided by the client.

What does insert return?

An SQL INSERT statement writes new rows of data into a table. If the INSERT activity is successful, it returns the number of rows inserted into the table.

What is Upsert in PostgreSQL?

The UPSERT statement is a DBMS feature that allows a DML statement's author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).


2 Answers

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

like image 148
mu is too short Avatar answered Sep 20 '22 15:09

mu is too short


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; 
like image 28
Blair Kjenner Avatar answered Sep 21 '22 15:09

Blair Kjenner