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?
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?
You can do so starting with Postgres 9.1:
In the meanwhile, if you're only interested in the id, you can do so with a trigger:
Tested with psql (10.3, server 9.6.8)
The best practice for this situation. Use
RETURNING … INTO
.You can use the
lastval()
function:So something like this:
This will work fine as long as no one calls
nextval()
on any other sequence (in the current session) between your INSERTs.As Denis noted below and I warned about above, using
lastval()
can get you into trouble if another sequence is accessed usingnextval()
between your INSERTs. This could happen if there was an INSERT trigger onTable1
that manually callednextval()
on a sequence or, more likely, did an INSERT on a table with aSERIAL
orBIGSERIAL
primary key. If you want to be really paranoid (a good thing, they really are you to get you after all), then you could usecurrval()
but you'd need to know the name of the relevant sequence:The automatically generated sequence is usually named
t_c_seq
wheret
is the table name andc
is the column name but you can always find out by going intopsql
and saying:and then looking at the default value for the column in question, for example:
FYI:
lastval()
is, more or less, the PostgreSQL version of MySQL'sLAST_INSERT_ID
. I only mention this because a lot of people are more familiar with MySQL than PostgreSQL so linkinglastval()
to something familiar might clarify things.In line with the answer given by Denis de Bernardy..
If you want id to be returned afterwards as well and want to insert more things into Table2: