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).

SqlData Integrity

Code

snippet
-- 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

FAQ

Which tables does the SQL touch?
The references are `orders`.