Sequence nextval Gaps Under Rollback
Identity and nextval never recycle numbers: rolled-back inserts leave permanent gaps, so count rows with count(*) instead of max(id).
Code
-- IDENTITY 底层是 nextval 序列:分配即消耗,永不回收
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY,
note text,
created_at timestamptz NOT NULL DEFAULT now()
);
BEGIN;
INSERT INTO orders (note) VALUES ('will roll back'); -- 序号被消耗
ROLLBACK;
INSERT INTO orders (note) VALUES ('after rollback'); -- 新行序号跳过被回滚的那个
-- 行为要点:
-- 1. 序号空洞是预期行为,连续性不是任何约束的一部分
-- 2. 不要用 max(id) 推断行数,用 count(*)
-- 3. GENERATED ALWAYS 不改变上面的行为
SELECT count(*) AS rows FROM orders;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with orders among the objects involved.
What the statements actually assemble: COUNT aggregation; NOT NULL qualifiers on the required columns; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the orders table.
Statements that matter
INSERT INTO orders (note) VALUES ('after rollback'); -- 新行序号跳过被回滚的那个
SELECT count(*) AS rows FROM orders;
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY,
note text,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (note) VALUES ('will roll back'); -- 序号被消耗
ROLLBACK;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- The references are `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.