How to Fix “nextval: reached maximum value of sequence” Error in PostgreSQL

In PostgreSQL, a commonly faced error “nextval: reached maximum value” error occurs when a sequence reaches its maximum value and the user is still trying to generate a new value. Postgres offers various methods to deal with the stated issue, such as resetting the sequence, altering the maximum value of the sequence, repeating the sequence, and so on.

This post will explain some useful methods to rectify the “nextval: reached maximum value” error in PostgreSQL.

How to Fix the “nextval: reached a maximum value of sequence” Error in Postgres?

We have created a sequence name example_seq whose details are enlisted in the following snippet:

\d example_seq;
img

Let’s execute the nextval() function to see how the stated error occurs in Postgres:

SELECT nextval('example_seq');
img

To fix the “nextval: reached a maximum value” error, the below-listed approaches can be used in Postgres:

- Method 1: Use Cycle Option
- Method 2: Alter the Sequence Maximum Value
- Method 3: Remove the MAXVALUE Option From the Sequence
- Method 4: RESTART the Sequence

Method 1: Use Cycle Option

Specifying the cycle option will restart the sequence once it reaches the maximum limit:

ALTER SEQUENCE example_seq
CYCLE;
img

Let’s confirm the sequence structure using the following command:

\d example_seq;
img

The output confirms that the “CYCLE” option has been enabled successfully. Let’s run the nextval() function once more:

SELECT nextval('example_seq');
img

The output shows that the sequence has been restarted from the starting value.

Method 2: Alter the Sequence Maximum Value

Increasing the maximum value of the sequence will also rectify the stated error:

ALTER SEQUENCE example_seq
MAXVALUE 500;
img

Now the stated error wouldn’t appear until the sequence reaches the specified maximum value.

Method 3: Remove the MAXVALUE Option From the Sequence

Removing the MAXVALUE option from the sequence will set the maximum value to the default(i.e. Default maximum value of the specified data type).

ALTER SEQUENCE example_seq
NO MAXVALUE;
img

In this case, the stated error wouldn’t appear until the sequence reaches the maximum value of the specified data type.

Method 4: RESTART the Sequence

Resetting the sequence value will restart the sequence from the beginning. To do this, utilize the ALTER SEQUENCE command with the RESTART argument:

ALTER SEQUENCE example_seq
RESTART;
img

The output verifies that the sequence has been reset successfully.

Conclusion

In PostgreSQL, a commonly faced error “nextval: reached maximum value” error occurs when a sequence reaches its maximum value and the user is still trying to generate a new value. In Postgres, various methods such as the “Cycle” option, “Altering the Maximum Value”, “Removing the MAXVALUE” option, and RESTART option are used. This post has provided several methods to fix the “nextval: reached maximum value” error in PostgreSQL.