Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use return value of INSERT...RETURNING in another INSERT?

Is something like this possible?

INSERT INTO Table2 (val) VALUES ((INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id)); 

like using the return value as value to insert a row in a second table with a reference to the first table?

like image 333
Eike Cochu Avatar asked Jul 03 '11 00:07

Eike Cochu


People also ask

What does Postgres return on insert?

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. But it can be very handy when relying on computed default values.

What does the insert () function return?

Returns the original string with specified text inserted at a specific byte location.

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).

What is the return type of insert query in SQL?

Description. INSERT ... RETURNING returns a resultset of the inserted rows. This returns the listed columns for all the rows that are inserted, or alternatively, the specified SELECT expression.


2 Answers

You can do so starting with Postgres 9.1:

with rows as ( INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id ) INSERT INTO Table2 (val) SELECT id FROM rows 

In the meanwhile, if you're only interested in the id, you can do so with a trigger:

create function t1_ins_into_t2()   returns trigger as $$ begin   insert into table2 (val) values (new.id);   return new; end; $$ language plpgsql;  create trigger t1_ins_into_t2   after insert on table1 for each row execute procedure t1_ins_into_t2(); 
like image 122
Denis de Bernardy Avatar answered Oct 21 '22 19:10

Denis de Bernardy


The best practice for this situation. Use RETURNING … INTO.

INSERT INTO teams VALUES (...) RETURNING id INTO last_id; 

Note this is for PLPGSQL

like image 24
Alexandre Assi Avatar answered Oct 21 '22 21:10

Alexandre Assi