How CURRVAL() Works in PostgreSQL

In PostgreSQL, the currval() function returns the value most recently returned by nextval() for the specified sequence in the current session.

The currval() function is very similar to the lastval() 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. The currval() on the other hand, only reports on the specified sequence.

Syntax

The syntax goes like this:

currval ( regclass ) 

Where regclass is the OID of the sequence from the pg_class system catalog view. However, Postgres allows us to pass the sequence name if we prefer. When we do this, Postgres will look up the OID behind the scenes. This eliminates the need for us to run joins across multiple tables to find its OID. 

Example

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

SELECT nextval('Sequence1');

Result:

 nextval 
---------
       7
(1 row)

We can see that it returned 7.

Let’s now call currval():

SELECT currval('Sequence1');

Result:

 currval 
---------
       7
(1 row)

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

Use the OID

In the above example I passed the name of the sequence. However, we can go right ahead and pass the OID directly:

SELECT currval(50355);

Result:

 currval 
---------
       7
(1 row)

When There’s No currval() for the Specified Sequence

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

To demonstrate, let’s create another sequence:

CREATE SEQUENCE Sequence2;

Now let’s immediately call currval() against that sequence:

SELECT currval('Sequence2');

Result:

ERROR:  currval of sequence "sequence2" is not yet defined in this session

As expected, we get an error.