PostgreSQL nextval() Function

The PostgreSQL nextval() function advances the specified sequence to its next value and returns that value. This operation is an atomic operation.

nextval() Syntax

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

nextval(sequence_name TEXT) -> BIGINT

Parameters

sequence_name

Required. The name of the sequence.

Return value

The PostgreSQL nextval() function advances the specified sequence to its next value and returns that value.

nextval() 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 advance my_sequence to its next value and return the latest value:

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

Since the starting value of my_sequence is 100, the first time the nextval() function is executed, it returns 100.

Let’s do it again:

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

Here, since we didn’t set the increment size for my_sequence when creating, the increment size of my_sequence is 1. So after executing the nextval() function , the latest value of the my_sequence sequence changed from 100 to 101.