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.

SqlData Integrity

Code

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

FAQ

Which relations are involved here?
The references are `order_lines`.