AI Hints
Home›PostgreSQL Tutorial›Upsert, Generated Columns, ALTER
PostgreSQL · Lesson 23 of 120

Generated Columns

Computed and stored.

⏱ 2 min read▶ Video at 19:14🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Each order item has a quantity and a price. The line total is always quantity times price. A generated column calculates it, and keeps it right automatically.

  • Quantity
  • Price
  • Total, always right

A line total column

Generated always as, then the formula. Stored means it's saved on disk, and updated whenever the row changes. Run it. Totals appear without us ever writing them.

query.sqlsql
CREATE TABLE cart (
  item     text,
  qty      integer,
  price    numeric(6,2),
  total    numeric(8,2) GENERATED ALWAYS AS (qty * price) STORED
);
INSERT INTO cart (item, qty, price) VALUES ('Mug', 2, 9.50), ('Tote bag', 1, 14.00);
SELECT * FROM cart;
Output
CREATE TABLE
INSERT 0 2
   item   | qty | price | total
----------+-----+-------+-------
 Mug      |   2 |  9.50 | 19.00
 Tote bag |   1 | 14.00 | 14.00
(2 rows)
Also uses _empty
1

Rules

The formula can only use columns from the same row. You can't write to a generated column. Postgres eighteen also adds virtual generated columns, which are computed when read, and not stored.

keyvalue
Formulasame row only
Writesnot allowed
STOREDsaved on disk
VIRTUALnew in PG 18

Summary

Generated columns compute values from other columns, and keep them right. Next, changing a table that already exists.

Key takeaways
  • GENERATED
  • STORED
  • Always right
Next up: ALTER TABLE — change a live table