Part 10 / Topic 7 of 9
Generated columns
A generated column is computed by the database from other columns — stored, always current, impossible to get wrong:
CREATE TABLE invoice_lines (
line_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
quantity integer NOT NULL,
unit_price numeric(10,2) NOT NULL,
line_total numeric(12,2) GENERATED ALWAYS AS (quantity * unit_price) STORED
);
INSERT INTO invoice_lines (quantity, unit_price) VALUES (3, 19.99), (1, 250.00);
SELECT * FROM invoice_lines;
CREATE TABLE
INSERT 0 2
line_id | quantity | unit_price | line_total
---------+----------+------------+------------
1 | 3 | 19.99 | 59.97
2 | 1 | 250.00 | 250.00
(2 rows)
Nobody inserted line_total; nobody may (writing to it errors). Where Part 9 warned that duplicating a derivable fact creates drift, a generated column is the safe version: derived, but by the engine, atomically, every time. Use it for totals, normalised search keys (lower(email)), extracted JSON fields — anywhere "computed from this row" would otherwise be re-implemented in three application codebases.
🧪 Quick quiz — answer from memory, then check.
- What happens if you INSERT a value into a generated column?
- Why is a generated column not a denormalization hazard?
Show the answers
- An error — the database owns it.
- It cannot drift: the engine recomputes it from the row itself on every write.
Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.