GENERATED Column
Last updated: 2026-11-04
GENERATED Column
A generated column hands the computation to the database: the value follows from an expression, so the application need not calculate it and the stored value can never drift from its inputs. Generated columns come as STORED (materialized) or VIRTUAL (computed on demand), with virtual columns newly supported in PostgreSQL 18. The column must be omitted when writing.
| Kind | constraint |
|---|---|
| Example Language | SQL |
📝 Syntax
`column_name type GENERATED ALWAYS AS (expression) STORED`
Virtual columns (PostgreSQL 18+): `GENERATED ALWAYS AS (expression) VIRTUAL`
⚙️ Parameters
| expression | The expression producing the column's value. It may reference other columns of the same row and must be immutable. |
|---|---|
| STORED / VIRTUAL | STORED materializes the computed value on disk (PostgreSQL 12+); VIRTUAL stores only the expression and computes on demand (introduced in PostgreSQL 18). |
Returns:A generated column returns nothing by itself — the database computes its value. Writing to it explicitly raises `cannot insert a non-DEFAULT value into column "..."`.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT 'stored total = quantity * unit_price' AS step,
(SELECT total::TEXT FROM invoices WHERE invoice_id = 1) AS result
UNION ALL SELECT 'write to generated column',
(SELECT pg_try('INSERT INTO invoices VALUES (2, 2, 5.00, 10.00)'))
UNION ALL SELECT 'rows stored',
(SELECT count(*)::TEXT FROM invoices)
step | result
--------------------------------------+-------------------------------------------------------
stored total = quantity * unit_price | 59.97
write to generated column | cannot insert a non-DEFAULT value into column "total"
rows stored | 1
(3 rows)
📌 Key Points
- Generated columns must be omitted on INSERT and UPDATE; assigning to them is rejected.
- A STORED column costs storage space but reads fast; a VIRTUAL column costs nothing on disk but is computed on every read.
- The expression must be immutable and cannot reference other tables or contain subqueries.
- Generated columns may reference other generated columns, but must be defined in dependency order with no cycles.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow is a generated column different from a view?
AA generated column belongs to the table: it has its own storage and type, can be indexed, referenced by foreign keys and queried directly. A view is a virtual query re-executed on every access and cannot be indexed directly without materializing it.
QAre PostgreSQL 18's virtual columns worth using?
AThey suit expensive derivations that are read rarely, such as a complex expression used only in occasional reports. For frequently read columns STORED is usually better, since it moves the cost to write time.