If you’re getting an error that reads something like “lastval is not yet defined in this session” when calling the lastval()
function in PostgreSQL, it’s probably because nextval()
hasn’t yet been called in the current session.
If you want to avoid this error, only call the lastval()
function when you know that nextval()
has been called at least once in the current session.
Example of Error
Here’s an example of code that produces the error:
SELECT lastval();
Result:
ERROR: lastval is not yet defined in this session
The reason that code produced the error is because I had only just opened a new PostgreSQL session via psql
and hadn’t yet called nextval()
.
Solution
The solution is to make sure that nextval()
has been called at least once in the current session.
So let’s do that:
SELECT nextval('Sequence1');
Result:
nextval --------- 7 (1 row)
I just used nextval()
to call a sequence called Sequence1
. We can see that it generated the value of 7
.
Now we can call lastval()
without error:
SELECT lastval();
Result:
lastval --------- 7 (1 row)
As expected, the value is the same as the one we got when we called nextval()
. That’s because it’s the last value that was returned by nextval()
in the current session.