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?
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.
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.
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.
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).
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With