To avoid blocking concurrent transactions that obtain numbers from
- the same sequence, a nextval operation is never
- rolled back; that is, once a value has been fetched it is considered
- used and will not be returned again. This is true even if the
- surrounding transaction later aborts, or if the calling query ends
- up not using the value. For example an INSERT with
+ 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. Such cases will leave
- unused holes
in the sequence of assigned values.
+ the ON CONFLICT rule instead.
Thus,
PostgreSQL sequence
objects cannot be used to obtain gapless
sequences.
- Likewise, any sequence state changes made by setval
- are not undone if the transaction rolls back.
+ 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.