Identity Columns GENERATED ALWAYS

Let GENERATED ALWAYS AS IDENTITY own primary keys: plain inserts get sequence values, explicit ids need OVERRIDING SYSTEM VALUE.

SqlData Integrity

Code

snippet
-- IDENTITY 主键由序列托底,应用侧不提供 id
CREATE TABLE invoices (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    reference text    NOT NULL
);

INSERT INTO invoices (reference) VALUES ('INV-001') RETURNING id; -- 1

-- GENERATED ALWAYS 下显式写 id 会被拒绝;数据迁移导入需要 OVERRIDING SYSTEM VALUE
INSERT INTO invoices (id, reference)
    OVERRIDING SYSTEM VALUE VALUES (9001, 'INV-LEGACY')
RETURNING id; -- 9001

-- 外部插入不会推进序列:下一个自动值仍然是 2
INSERT INTO invoices (reference) VALUES ('INV-002') RETURNING id; -- 2

What the code does

Several statements share this file — INSERT / CREATE, with invoices among the objects involved.

Mechanically, the statements are built from: a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

Run it in the invoices database context.

Key statements

CREATE TABLE invoices (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    reference text    NOT NULL
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`invoices` — referenced directly, no join needed.