PostgreSQL – How to Get Current and Next Values of Sequence
You can use Sequences to generate unique integer values, often used as auto-incrementing primary keys in tables. You can obtain the current value and the next value of a sequence using the currval
and nextval
functions, respectively. These functions are typically used within SQL statements or in PL/pgSQL code.
Current Value (currval
): To get the current value of a sequence, you need to specify the name of the sequence as an argument to the currval
function. Here’s the syntax:
SELECT currval('sequence_name');
Replace 'sequence_name'
with the actual name of the sequence you want to check. Note that you should have already called nextval
on the sequence in the current session before using currval
to retrieve its current value.Example:
SELECT currval('my_sequence');
Next Value (nextval
): To get the next value of a sequence and increment the sequence, you can use the nextval
function. Here’s the syntax:
SELECT nextval('sequence_name');
Again, replace 'sequence_name'
with the name of the sequence you want to retrieve the next value for.Example:
SELECT nextval('my_sequence');
- You should use
nextval
to advance the sequence before usingcurrval
, ascurrval
retrieves the last value generated bynextval
within the current session. - If you attempt to use
currval
without having previously callednextval
in the current session or if the sequence has not been used in the current session at all, it will result in an error. - Sequences are typically associated with specific columns in tables, so you would use these functions in the context of an
INSERT
statement to generate auto-incrementing primary key values.