Skip to content

Sequences

A sequence is a standalone database object that hands out unique, monotonically increasing numbers. In PostgreSQL it is the machinery behind every BIGSERIAL and GENERATED AS IDENTITY column.

Key Characteristics

Independent object: A sequence exists separately from any table. \ds lists them; they can be granted on, altered, and dropped on their own.

Non-transactional: nextval() does not roll back. This is deliberate — if it did, concurrent writers would block each other waiting to see whether you committed. The consequence is permanent gaps.

Lock-free under concurrency: Each backend takes a small cached block of values (CACHE n) and serves from memory, so parallel inserts don't contend on a single counter.

The Three Ways to Declare One

-- 1. IDENTITY — SQL-standard, preferred for new tables
CREATE TABLE users (
  id   BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name TEXT NOT NULL
);

-- 2. BIGSERIAL — older PostgreSQL idiom, still everywhere
CREATE TABLE users (
  id   BIGSERIAL PRIMARY KEY,
  name TEXT NOT NULL
);

-- 3. Explicit sequence — when you need to share it across tables
CREATE SEQUENCE order_ref_seq START 1000 INCREMENT BY 1;
INSERT INTO orders (ref) VALUES (nextval('order_ref_seq'));

Prefer GENERATED ALWAYS AS IDENTITY. Unlike BIGSERIAL it rejects a manual insert into the column unless you write OVERRIDING SYSTEM VALUE, which stops the classic bug where application code inserts an explicit id and desynchronises the sequence from the table.

GENERATED BY DEFAULT AS IDENTITY is the permissive variant — use it when a data-migration tool needs to write explicit ids.

Working With Them

SELECT nextval('order_ref_seq');   -- advance and return
SELECT currval('order_ref_seq');   -- last value THIS session got
SELECT last_value FROM order_ref_seq;

-- Find the sequence behind a column
SELECT pg_get_serial_sequence('users', 'id');

-- Resync after a bulk load that wrote explicit ids
SELECT setval(pg_get_serial_sequence('users','id'),
              (SELECT COALESCE(MAX(id), 1) FROM users));

Gotchas

Gaps are normal, not corruption

A rolled-back transaction consumes its id forever. So does a crash — cached-but-unissued values are lost, so the counter can jump by up to CACHE n. Never expose a sequence value as a gapless invoice or receipt number; a regulator asking "where is invoice 4,812?" is not a conversation you want. Derive those from a separate counter table updated inside the transaction.

  • currval() is per-session. It errors until that session has called nextval(). It is not "the current global value" — use last_value for that.
  • Logical replication does not replicate sequence state. After a failover to a logical replica, sequences sit where they were when the subscription started. Call setval() as part of cutover or the first insert will collide with existing rows.
  • ALTER SEQUENCE ... RESTART is not transactional either — it takes effect immediately for all sessions.
  • BIGINT, not INT. SERIAL caps at 2.1 billion. PostgreSQL has no unsigned types, so there is no "drop the sign to double it" escape hatch — migrating a live INT PK to BIGINT is a full table rewrite. Start at BIGINT.

When a Sequence Is the Wrong Tool

Sequences are a single logical counter, which makes them awkward in two cases:

Need Reach for
Ids generated client-side, or before the DB round-trip UUIDv7 / ULID
Ids that must not leak volume or ordering publicly UUIDv7, or a separate opaque public id
Multi-primary or sharded writes UUIDv7, or per-shard sequence offsets (START 1 INCREMENT BY 100)
Strictly gapless business numbering A counter row updated in-transaction, accepting the write contention

See Bigint vs UUIDv7 Id Strategy for the full trade-off.

The MySQL contrast

MySQL has no sequence object — it uses a per-table AUTO_INCREMENT counter instead. Two differences matter when porting: the counter cannot be shared across tables, and ALTER TABLE resets it to MAX(id) + 1, so deleting the newest rows silently causes id reuse. PostgreSQL sequences never reuse a value on their own.