1.Sequences and Generated Identifiers
A sequence is its own database object that generates a new, incrementing integer every time it is asked, via nextval(). It exists independently of any table — a column with a DEFAULT of nextval('some_sequence') is simply a column that asks the sequence for the next value on every INSERT that omits it.
Key features
- A sequence is created with CREATE SEQUENCE and generates values via nextval('sequence_name')
- A sequence has its own current value, increment, min/max, and can be queried directly
- SERIAL and GENERATED ... AS IDENTITY both create a sequence automatically and wire a column's DEFAULT to it — they are convenience syntax, not a different underlying mechanism
- nextval() is guaranteed to return a unique value across concurrent callers, without any locking that would block other inserters
- A sequence advances even if the transaction that called nextval() is rolled back — sequence advancement is not transactional
A sequence vs a column relying on it
- orders_id_seq — a standalone sequence object
- leads to nextval(...)
- nextval(...) — requests the next value, atomically
- leads to id column DEFAULT
- id column DEFAULT — used automatically on INSERT if omitted
Command
CREATE SEQUENCE orders_id_seq;
CREATE TABLE orders (id INT DEFAULT nextval('orders_id_seq') PRIMARY KEY, total NUMERIC);
SELECT nextval('orders_id_seq'); -- can be called independently of any tableA sequence is its own standalone object with persistent state, independent of any table — SERIAL/IDENTITY are convenience syntax that create one automatically and wire a column's DEFAULT to it, not a different underlying mechanism.