lastval() is a system function returning the value most recently returned by
nextval() in the current session, regardless of which sequence was called.
lastval() was added in PostgreSQL 8.1.
lastval () →
The value of the last sequence for which
nextval() was called will be returned.
An error will be raised if
nextval() was not yet called for any sequence in the current session.
lastval() is similar to MySQL's
LAST_INSERT_ID() function. Note however that it will be generally more reliable and efficient to use the
RETURNING clause to directly retrieve a value generated by
nextval() during an
Basic usage example for
postgres=# CREATE SEQUENCE foo_seq; CREATE SEQUENCE postgres=# CREATE SEQUENCE bar_seq MINVALUE 99; CREATE SEQUENCE postgres=# SELECT nextval('bar_seq'); nextval --------- 99 (1 row) postgres=# SELECT lastval(); lastval --------- 99 (1 row) postgres=# SELECT nextval('foo_seq'); nextval --------- 1 (1 row) postgres=# SELECT lastval(); lastval --------- 1 (1 row)
ERROR will be raised if
nextval() was not previously called:
postgres=# SELECT lastval(); ERROR: lastval is not yet defined in this session
RETURNING clause rather than
lastval() than to explicitly return the value generated by a particular sequence during an
postgres=# CREATE TABLE foo (id INT NOT NULL DEFAULT nextval('foo_seq')); CREATE TABLE postgres=# INSERT INTO foo VALUES (DEFAULT) RETURNING id; id ---- 2 (1 row)