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;| qty | unit_price | total |
|---|---|---|
| 5 | 1 | 5 |
| 2 | 4 | 8 |
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 purposetext
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;| qty | unit_price | total |
|---|---|---|
| 2 | 4 | 8 |
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