lastval()

A function returning the value most recently returned by nextval()

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.

Usage

lastval () → bigint

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 INSERT or UPDATE operation.

Change history

Examples

Basic usage example for lastval():

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)

An ERROR will be raised if nextval() was not previously called:

postgres=# SELECT lastval();
ERROR:  lastval is not yet defined in this session

Use the RETURNING clause rather than lastval() than to explicitly return the value generated by a particular sequence during an INSERT or UPDATE operation:

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)

Categories

Sequences, System function

See also

currval(), setval(), nextval()