← 中文资源

简体中文版本

setval 把序列同步到 max(id)

用 OVERRIDING SYSTEM VALUE 批量导入历史主键后,序列仍停在起点:pg_get_serial_sequence 配合 setval 拨到 max(id),下次 nextval 自动返回 max+1。

阅读英文原文

实现说明

这个文件依次执行 INSERT / CREATE 语句,涉及 invoices。 invoices 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。 用到的 SQL 构件:RETURNING 把受影响的行交回调用方;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

这个文件引用了哪些表?

invoices——名字即引用,连接不在流程里。

核心语句

SELECT setval(
    pg_get_serial_sequence('invoices', 'id'),
    (SELECT max(id) FROM invoices)
);
INSERT INTO invoices (id, label) OVERRIDING SYSTEM VALUE VALUES
    (1, 'imported-1'), (2, 'imported-2'), (3, 'imported-3');
CREATE TEMP TABLE invoices (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    label text NOT NULL
);

代码示例

-- after a bulk import bypasses IDENTITY auto-assignment: the sequence still sits at its old position,
-- so the next ordinary insert would hit the primary key. setval moves the sequence to max(id) in the table
CREATE TEMP TABLE invoices (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    label text NOT NULL
);

-- simulate the import: load historical primary keys (GENERATED ALWAYS needs OVERRIDING SYSTEM VALUE)
INSERT INTO invoices (id, label) OVERRIDING SYSTEM VALUE VALUES
    (1, 'imported-1'), (2, 'imported-2'), (3, 'imported-3');

-- the sequence's "current value" and the table data are out of sync at this point
SELECT pg_get_serial_sequence('invoices', 'id') AS seq_name;

-- setval(seq, max(id)): with is_called=true semantics, the next nextval returns max+1
SELECT setval(
    pg_get_serial_sequence('invoices', 'id'),
    (SELECT max(id) FROM invoices)
);

-- ordinary inserts resume: the next one gets 4 automatically, no unique violation
INSERT INTO invoices (label) VALUES ('new-after-import')
RETURNING id;