In PostgreSQL, the “CURRVAL()” function is a built-in function that aids in working with sequences. It retrieves the most recently obtained value from the “NEXTVAL()” function for a specific sequence within the current session. This function is session-specific, which means it only retrieves the last value of a sequence fetched within the current session. However, calling the CURRVAL() function before NEXTVAL() function in the current session will lead you to the “currval of the sequence is not yet defined in this session” error.
This write-up illustrates a complete process of fixing the “currval of sequence is not yet defined in this session” error in PostgreSQL.
How to Fix “currval of sequence is not yet defined” Error When Calling/Invoking CURRVAL() in Postgres?
The stated error occurs when the CURRVAL() function is invoked before the NEXTVAL() function. For better understanding, let’s create a new sequence and apply the CURRVAL() function to it:
CREATE SEQUENCE commandprompt;
The below snippet shows that when the NEXTVAL() function is not used in the current session then directly invoking the CURRVAL() function will throw the stated error:
SELECT CURRVAL('commandprompt');
To fix the stated error, all you need to do is invoke the NEXTVAL() function before the CURRVAL() function at least once:
SELECT NEXTVAL('commandprompt'), NEXTVAL('commandprompt');
In this example, the NEXTVAL() function is invoked a couple of times:
Now invoke the CURRVAL() function to see how it works:
SELECT CURRVAL('commandprompt');
The output snippet shows that the “CURRVAL” function shows the last retrieved value of the NEXTVAL() function in the current session:
That’s all about fixing the “currval of sequence is not yet defined in this session” error in PostgreSQL.
Conclusion
In PostgreSQL, the “currval of sequence is not yet defined in this session” error occurs when the CURRVAL() function is invoked/called prior to the NEXTVAL() function. To fix the stated error, all you need to do is invoke the NEXTVAL() function before the CURRVAL() function at least once. This write-up has illustrated the complete process of fixing the “currval of sequence is not yet defined in this session” error in PostgreSQL.