RETURNING
With a serial
or IDENTITY
column, you can return the generated ID from the same command:
INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;
See:
Explicitly fetch value
If filename
needs to include tbl_id
(redundantly), you can still use a single query.
Use lastval()
or the more specific currval()
:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq') -- or lastval()
RETURNING tbl_id;
See:
If multiple sequences may be advanced in the process (even by way of triggers or other side effects) the sure way is to use currval('tbl_tbl_id_seq')
.
If you don't know the sequence name:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;
'tbl_tbl_id_seq' is the default name for a table 'tbl' with a serial column 'tbl_id'. But there are no guarantees. A column default can fetch values from any sequence if so defined. Also, if the default name is taken when creating the table, Postgres picks the next free name according to a simple algorithm.
'tbl_tbl_id_seq'
must be visible in the the current search_path
, else you must schema-qualify.
fiddle
nextval
call that's used in an insert, because unlikeINSERT ... RETURNING
both will work via query generation engines and other painful things that may not understand theRETURNING
extension :S – BlackstoneRETURNING
clause (which has been around for years now!), it may be outdated as well - or just a very poor crutch that's looking for replacement. Still, it's good to have the fallback solution a_horse provided. No argument there. – Padre