In PostgreSQL, different inbuilt functions are used to work with the sequences. One such function is the “LASTVAL()” function which retrieves the most recently generated sequence value of the current session. The LASTVAL() function is session-specific which means it retrieves the last value of a sequence fetched within the current session only.
This write-up explains the use of the LASTVAL() function in Postgres.
What Does the LASTVAL() Function Do in PostgreSQL?
The LASTVAL() function in PostgreSQL operates in a manner similar to the CURRVAL() function but with a notable distinction. The CURRVAL() function requires the specification of the sequence name, while the LASTVAL() function executes without a sequence name.
The reason for this distinction is that the LASTVAL() function in Postgres does not provide information about a specific sequence. Rather, it retrieves the value from the most recent usage of the NEXTVAL() function within the current session, irrespective of the particular sequence utilized.
Syntax
To use LASTVAL() function, specify the function name along with a set of parentheses:
LASTVAL();
The above syntax states that the stated function doesn’t accept any arguments.
Example 1: How to Use LASTVAL() Function in Postgres?
In the following snippet, the NEXTVAL() function is invoked against the “example_1” sequence:
SELECT NEXTVAL('example_1');
Now use the LASTVAL() function to get the value from the most recent usage of the NEXTVAL() function within the current session:
SELECT LASTVAL();
The LASTVAL() function retrieves “1”, which is the last returned value of the NEXTVAL() function:
Example 2: LASTVAL is Not Yet Defined Error in Postgres
If the NEXTVAL() is not used in the current session then invoking the LASTVAL() function will lead you to the following error:
That’s all about the usage of the LASTVAL() function in PostgreSQL.
Conclusion
In PostgreSQL, “LASTVAL()” is a built-in function that retrieves the most recently generated sequence value of the current session. It is session-specific which means it retrieves the last value of a sequence fetched within the current session only. If the NEXTVAL() is not used in the current session then invoking the LASTVAL() function will lead you to the “LASTVAL is not yet defined” error. This post has explained how the LASTVAL() function works in Postgres.