PostgreSQL currval() Function

The PostgreSQL currval() function returns the current value of the specified sequence in the current session. If the current session has not called the nextval() function, an error will occur.

currval() Syntax

Here is the syntax of the PostgreSQL currval() function:

currval(sequence_name TEXT) -> BIGINT

Parameters

sequence_name

Required. The name of the sequence.

Return value

The PostgreSQL currval() function returns the current value of the specified sequence in the current session.

An error will occur if the nextval() function has not been called in the current session.

currval() Examples

First, let’s create a simple sequence generator named my_sequence using the CREATE SEQUENCE statement:

DROP SEQUENCE IF EXISTS my_sequence;
CREATE SEQUENCE my_sequence START 100;

Here, we create a sequence generator named my_sequence with a starting value of 100.

Then, let’s use the PostgreSQL nextval() function to use the next value and return the latest value of my_sequence:

SELECT nextval('my_sequence');
 nextval
---------
     100

Let’s use the currval() function to return the current value of the sequence my_sequence:

SELECT currval('my_sequence');
 currval
---------
     100

Here, the return value of the currval() function is the same as the return value of the most recent nextval() function.