← Back to SQL, page 10

sql-0181 · Medium mid

What are generated columns, and when would you use one?

A generated column is computed from other columns in the same row, declared with GENERATED ALWAYS AS (expr). VIRTUAL columns are computed on read; STORED columns are computed on write and saved. They keep derived values such as a line total or a lowercased email consistent and can be indexed.

Full answer
sql
CREATE TABLE lines (
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL,
  total      INTEGER GENERATED ALWAYS AS (qty * unit_price) VIRTUAL
);
INSERT INTO lines (qty, unit_price) VALUES (2, 4), (5, 1);
SELECT qty, unit_price, total FROM lines ORDER BY total;
qtyunit_pricetotal
515
248

total is always qty * unit_price; there is no way to store a wrong value in it. Writing to it directly is an error:

sql
CREATE TABLE l2 (qty INTEGER, unit_price INTEGER, total INTEGER GENERATED ALWAYS AS (qty * unit_price));
INSERT INTO l2 (qty, unit_price, total) VALUES (1, 1, 99);
-- error on purpose
text
Error: cannot INSERT into generated column "total"

SQLite supports VIRTUAL (the default) and STORED. PostgreSQL 12 to 17 supports STORED only:

sql
CREATE TABLE lines (qty int, unit_price int, total int GENERATED ALWAYS AS (qty * unit_price) STORED);
INSERT INTO lines (qty, unit_price) VALUES (2, 4);
SELECT qty, unit_price, total FROM lines;
qtyunit_pricetotal
248

Typical uses: normalized search keys (lower(email)), extracted JSON fields, and totals that reports filter on. The expression must be deterministic and can only use the current row.

sql
CREATE TABLE lines (
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL,
  total      INTEGER GENERATED ALWAYS AS (qty * unit_price) VIRTUAL
);
INSERT INTO lines (qty, unit_price) VALUES (2, 4), (5, 1);
SELECT qty, unit_price, total FROM lines ORDER BY total;

-- error on purpose
CREATE TABLE l2 (qty INTEGER, unit_price INTEGER, total INTEGER GENERATED ALWAYS AS (qty * unit_price));
INSERT INTO l2 (qty, unit_price, total) VALUES (1, 1, 99);

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • GENERATED ALWAYS AS computes a column from the row
  • VIRTUAL computes on read; STORED saves on write
  • Generated columns cannot be written directly
  • They can be indexed

Common mistakes

  • Using non-deterministic functions such as random() in the expression
  • Expecting a generated column to read other tables

Follow-ups

  • How do generated columns compare with views?
  • Would you index a VIRTUAL column?

Tips

  • Mention the consistency benefit