Generated Columns Stored On Write
Compute a column at write time with GENERATED ALWAYS AS ... STORED; reads pay no calculation and attempts to insert an explicit value are rejected.
Code
-- GENERATED ALWAYS AS ... STORED:写行时计算并落盘,读取零计算
CREATE TABLE order_lines (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
unit_price_cents integer NOT NULL,
quantity integer NOT NULL CHECK (quantity > 0),
line_total_cents integer GENERATED ALWAYS AS
(unit_price_cents * quantity) STORED
);
-- 显式写生成列会被拒绝:值只能由表达式推导
INSERT INTO order_lines (unit_price_cents, quantity, line_total_cents)
VALUES (2500, 3, 9999);
INSERT INTO order_lines (unit_price_cents, quantity)
VALUES (2500, 3)
RETURNING line_total_cents; -- 7500:由生成列计算得出What the code does
Several statements share this file — INSERT / CREATE, with order_lines among the objects involved.
What the statements actually assemble: a RETURNING clause that hands the affected rows back to the caller; a CHECK constraint that rejects out-of-domain values at write time; 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
The order_lines table is the working surface here.
Key statements
CREATE TABLE order_lines (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
unit_price_cents integer NOT NULL,
quantity integer NOT NULL CHECK (quantity > 0),
line_total_cents integer GENERATED ALWAYS AS
(unit_price_cents * quantity) STORED
);
INSERT INTO order_lines (unit_price_cents, quantity, line_total_cents)
VALUES (2500, 3, 9999);
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?
- The references are `order_lines`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.