PostgreSQL lastval() Function
The PostgreSQL lastval()
function returns the result of the most recent nextval()
function . If the current session has not called the nextval()
function , an error will occur.
The lastval()
function is similar to the currval()
functions, except the lastval()
function do not need to specify a sequence name.
lastval()
Syntax
Here is the syntax of the PostgreSQL lastval()
function:
lastval() -> BIGINT
Parameters
The PostgreSQL lastval()
function does not require any parameters.
Return value
The PostgreSQL lastval()
function returns the result of the result of most recent nextval()
function.
An error will occur if the nextval()
function has not been called in this session.
lastval()
Examples
First, let’s create a simple sequence generator named my_sequence
using the CREATE SEQUENCE
statement:
DROP SEQUENCE IF EXISTS my_sequence;
CREATE SEQUENCE my_sequence START 100;
Here, we create a sequence generator named my_sequence
with a starting value of 100.
Then, let’s use the PostgreSQL nextval()
function to use the next value and return the latest value of my_sequence
:
SELECT nextval('my_sequence');
nextval
---------
100
Let’s use the lastval()
function to return the current value of the my_sequence
sequence:
SELECT lastval();
lastval
---------
100
Here, the return value of the lastval()
function is the same as the return value of the most recent nextval()
function.