nextval
PG 7.4+→ bigintAdvances the sequence and returns the new value. The sequence is updated even if the transaction is rolled back.
Signature
nextval ( regclass ) → bigintParameters
| Parameter | Type | Description |
|---|---|---|
| sequence_name | regclass (text or OID) | Name of the sequence (quoted if needed) |
Examples
SELECT nextval('my_seq');1 (or next value)INSERT INTO orders (id, ...) VALUES (nextval('order_id_seq'), ...);Inserts with next sequence value-- Preallocate a batch of IDs for bulk inserts
SELECT nextval('item_seq') FROM generate_series(1, 10);10 consecutive sequence values (may have gaps from concurrent sessions)-- Check what value will come next without advancing the sequence
SELECT last_value + increment_by FROM pg_sequences WHERE sequencename = 'my_seq';Predicted next value without consuming itSequences are non-transactional by design. Every `nextval` call permanently advances the counter, even inside a transaction that is later rolled back, aborted due to an error, or part of a connection that drops mid-flight. Applications that treat sequence values as a dense, gap-free range — for example, using them as invoice numbers for auditors — will occasionally discover missing numbers and have no explanation for them.
✓ Instead: Accept that gaps are normal and inevitable. If you need a truly gap-free, auditable number (e.g., legal invoice numbering), maintain a separate counter table inside the same transaction as the business record, using `SELECT ... FOR UPDATE` to serialize access. For most cases, just document to stakeholders that gaps in sequence-backed IDs are expected behaviour, not data loss.
`nextval` always advances the sequence, even if the calling transaction is rolled back. This is intentional — it prevents sequence deadlocks. Don't assume your sequence values will be gapless.
SELECT nextval('order_id_seq'); -- This sequence value is consumed even if your transaction failsSequence gaps are normal and expected