How LASTVAL() Works in PostgreSQL

In PostgreSQL, the lastval() function returns the value most recently returned by nextval() in the current session.

The lastval() function is very similar to the currval() function, except that lastval() doesn’t require the name of a sequence like currval() does. That’s because lastval() doesn’t report on any particular sequence – it reports on the last time nextval() was used in the current session, regardless of which sequence was used.

Syntax

The syntax goes like this:

lastval ()

So it doesn’t require or accept any arguments.

Example

Suppose we use nextval() against a sequence called Sequence1:

SELECT nextval('Sequence1');

Result:

 nextval 
---------
       6
(1 row)

We can see that it returned 6.

Let’s now call lastval():

SELECT lastval();

Result:

 lastval 
---------
       6
(1 row)

We get 6 because that’s the value that was returned the last time nextval() was called in this session.

Advance a Different Sequence

To demonstrate lastval() further, let’s use nextval() on another sequence, and then call lastval() again.

First, we’ll create the sequence, then we’ll use nextval() to advance the sequence to its next value and return the result:

CREATE SEQUENCE Sequence2;
SELECT nextval('Sequence2');

Result:

 nextval 
---------
       1

When I created the sequence I used the default settings, and so when I called nextval() for the first time it returned 1.

Now let’s call lastval() again:

SELECT lastval();

Result:

 lastval 
---------
       1
(1 row)

We can see that it reflects the value that nextval() last returned in the current session.

When There’s No lastval() for the Current Session

If nextval() hasn’t been used in the current session, there’ll be no value for lastval(). In such cases, an error is returned.

To demonstrate this, here’s what happens when I open a new session, then immediately call lastval():

SELECT lastval();

Result:

ERROR:  lastval is not yet defined in this session

As expected, we get an error.