nextval()
A function returning the next value in a sequence
nextval()
is a system function returning the next value in a sequence.
nextval()
was added in PostgreSQL 6.1.
Usage
nextval (regclass
) →bigint
Each value returned by nextval()
is returned atomically, i.e. each invocation will return a distinct value, even if executed in different sessions.
While it's possibly to execute nextval()
directly, usually it is used as a default value on a column.
The current value of a sequence can be retrieved without advancing the sequence with the currval()
function. It can be set explicitly using setval()
.
Change history
- PostgreSQL 6.1
- added (commit e8647c45)
Examples
Basic usage example for nextval()
:
postgres=# CREATE SEQUENCE foo_seq; CREATE SEQUENCE postgres=# SELECT nextval('foo_seq'); nextval --------- 1 (1 row)
Using nextval()
to generate a default value for a column in a table:
postgres=# CREATE TABLE foo (id INT DEFAULT nextval('foo_seq')); CREATE TABLE postgres=# INSERT INTO foo (id) VALUES (DEFAULT); INSERT 0 1 postgres=# SELECT * FROM foo; id ---- 2 (1 row)
References
- PostgreSQL documentation: Sequence Functions
Useful links
- ERROR: nextval: reached maximum value of sequence - September 2022 blog article by Hans-Jürgen Schönig / CyberTec