Sequences, IDENTITY & Serial Keys in SQL
Gap-free is a myth β order, not contiguity
Surrogate keys ride sequences: IDENTITY (standard, GENERATED ALWAYS AS IDENTITY) or SERIAL (PG legacy) or explicit CREATE SEQUENCE. NEXTVAL hands ordered, non-transactional numbers β rollbacks burn gaps, replicas cache blocks. Gap-free numbering needs locked counters (slow) β order without contiguity is the production contract. UUIDv7 ordered variants bridge distributed needs.
IDENTITY default
BIGINT GENERATED ALWAYS AS IDENTITY PK β ordered, atomic, session-safe.
Sequences explicit
CREATE SEQUENCE for app-controlled blocks (order numbers).
Gaps by design
Rollback/cache/concurrency burn values β order, not contiguity.
RETURNING not max+1
Fetch drawn ids in-statement; max(id)+1 races across sessions.
1CREATE TABLE orders (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY);2INSERT INTO orders DEFAULT VALUES RETURNING id;
| id |
|---|
| 1 |
| 2 |
Each insert draws the next sequence value atomically with RETURNING β no max+1 race. A rolled-back insert burns its number; the next commit skips it by design.
Draw + return atomically
No cross-session race.
1INSERT INTO orders DEFAULT VALUES RETURNING id;
| id |
|---|
| 1001 |
| 1002 |
Gaps are healthy
Contiguity demands locks; order does not.
1-- gaps from: ROLLBACK, cache blocks, concurrent takes
| id | fate |
|---|---|
| 1001 | committed |
| 1003 | 1002 burned by rollback |
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.