9.17. Sequence Manipulation Functions
This section describes functions for operating on sequence objects, also called sequence generators or just sequences. Sequence objects are special single-row tables created with CREATE SEQUENCE. Sequence objects are commonly used to generate unique identifiers for rows of a table. The sequence functions, listed in Table 9.55, provide simple, multiuser-safe methods for obtaining successive sequence values from sequence objects.
Table 9.55. Sequence Functions
Function Description |
---|
Advances the sequence object to its next value and returns that value. This is done atomically: even if multiple sessions execute This function requires |
Sets the sequence object's current value, and optionally its SELECT setval('myseq', 42); Next The result returned by This function requires |
Returns the value most recently obtained by This function requires |
Returns the value most recently returned by This function requires |
Caution
To avoid blocking concurrent transactions that obtain numbers from the same sequence, the value obtained by nextval
is not reclaimed for re-use if the calling transaction later aborts. This means that transaction aborts or database crashes can result in gaps in the sequence of assigned values. That can happen without a transaction abort, too. For example an INSERT
with an ON CONFLICT
clause will compute the to-be-inserted tuple, including doing any required nextval
calls, before detecting any conflict that would cause it to follow the ON CONFLICT
rule instead. Thus, Postgres Pro sequence objects cannot be used to obtain “gapless” sequences.
Likewise, sequence state changes made by setval
are immediately visible to other transactions, and are not undone if the calling transaction rolls back.
If the database cluster crashes before committing a transaction containing a nextval
or setval
call, the sequence state change might not have made its way to persistent storage, so that it is uncertain whether the sequence will have its original or updated state after the cluster restarts. This is harmless for usage of the sequence within the database, since other effects of uncommitted transactions will not be visible either. However, if you wish to use a sequence value for persistent outside-the-database purposes, make sure that the nextval
call has been committed before doing so.
The sequence to be operated on by a sequence function is specified by a regclass
argument, which is simply the OID of the sequence in the pg_class
system catalog. You do not have to look up the OID by hand, however, since the regclass
data type's input converter will do the work for you. See Section 8.19 for details.