Identity Columns GENERATED ALWAYS
Let GENERATED ALWAYS AS IDENTITY own primary keys: plain inserts get sequence values, explicit ids need OVERRIDING SYSTEM VALUE.
Code
-- 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; -- 2What 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
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 relations are involved here?
- `invoices` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.