What Does the CURRVAL() Function Do in PostgreSQL?

In PostgreSQL, a wide range of built-in functions are available to facilitate working with sequences. One such function is the “CURRVAL()” function which returns the most recently retrieved value of the NEXTVAL() function for a specific sequence in the current session. It is a session-specific function which means it will retrieve the last value of a sequence fetched within the current session only.

This write-up explains the use of the CURRVAL() function in Postgres.

What Does the CURRVAL() Function Do in PostgreSQL?

The CURRVAL() function in PostgreSQL operates in a manner similar to the LASTVAL() function but with a significant distinction. The CURRVAL() function accepts the sequence name as an argument, while the LASTVAL() function doesn’t require any sequence name. This is because the CURRVAL() function specifically reports on the value of a particular sequence.

Use the below-depicted syntax to execute the “CURRVAL()” function:

CURRVAL('seq_name');

The above syntax states that the stated function accepts sequence name as an argument.

Example 1: How to Use CURRVAL() Function in Postgres?

In the below snippet, the NEXTVAL() function is invoked against the “example_1” sequence:

SELECT NEXTVAL('example_1');
img

Use the CURRVAL() function with the sequence name to obtain the value from the latest invocation of the NEXTVAL() function in the current session:

SELECT CURRVAL('example_1');

The CURRVAL() function retrieves “3”, which is the last returned value of the NEXTVAL() function in the current session:

img

Example 2: CURRVAL is Not Yet Defined Error in Postgres

Let’s create a new sequence and apply the CURRVAL() function to it:

CREATE SEQUENCE commandprompt;
img

If the NEXTVAL() is not used in the current session then directly invoking the CURRVAL() function will throw the following error:

SELECT CURRVAL('commandprompt');
img

That’s all about the use of the CURRVAL() function in Postgres.

Conclusion

In PostgreSQL, “CURRVAL()” is a built-in function that returns the most recently retrieved value of the NEXTVAL() function for a specific sequence in the current session. It is a session-specific function 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 CURRVAL() function will cause the “CURRVAL is not yet defined” error. This post has explained how the CURRVAL() function works in Postgres.