Reading history

SQL Generated Columns

5 min read 0 views

Learn how generated columns calculate values from other columns automatically, the difference between STORED and VIRTUAL, indexing them, and their rules.

A shop’s order line has a unit price and a quantity. The line total is simply price × quantity. If you store the total as a normal column, sooner or later someone updates the quantity and forgets the total, and the numbers disagree. A generated column fixes this: the database calculates the value from other columns, so it can never be wrong.

In this lesson you will learn

  • How to declare a generated column
  • The difference between STORED and VIRTUAL
  • How generated columns update automatically
  • How to index a generated column
  • Rules and limits, and support in other databases

You should know CREATE TABLE and string functions.

Declaring a Generated Column

Write the column name, its type, then GENERATED ALWAYS AS (expression), followed by STORED or VIRTUAL.

CREATE TABLE order_lines (
  id         INTEGER PRIMARY KEY,
  item       TEXT    NOT NULL,
  unit_price INTEGER NOT NULL,
  qty        INTEGER NOT NULL,
  line_total INTEGER GENERATED ALWAYS AS (unit_price * qty) STORED,
  vat        REAL    GENERATED ALWAYS AS (round(unit_price * qty * 0.15, 2)) VIRTUAL
);
INSERT INTO order_lines (item, unit_price, qty) VALUES
  ('Notebook', 60, 5), ('Pen', 15, 12), ('Calculator', 950, 1);
SELECT item, unit_price, qty, line_total, vat FROM order_lines;

-- Change the inputs and the generated columns follow
UPDATE order_lines SET qty = 10 WHERE item = 'Notebook';
SELECT item, qty, line_total, vat FROM order_lines WHERE item = 'Notebook';

Output

+------------+------------+-----+------------+-------+
| item       | unit_price | qty | line_total | vat   |
+------------+------------+-----+------------+-------+
| Notebook   | 60         | 5   | 300        | 45.0  |
| Pen        | 15         | 12  | 180        | 27.0  |
| Calculator | 950        | 1   | 950        | 142.5 |
+------------+------------+-----+------------+-------+
(3 rows)

+----------+-----+------------+------+
| item     | qty | line_total | vat  |
+----------+-----+------------+------+
| Notebook | 10  | 600        | 90.0 |
+----------+-----+------------+------+
(1 row)
  • The INSERT gives only the item, price and quantity. line_total and vat are filled in by the database.
  • After the quantity changed to 10, both generated values changed with it. No one had to remember.
  • The 15% VAT here is just an example rate; real rates depend on the product and the law.

STORED or VIRTUAL?

STOREDVIRTUAL
When it is calculatedWhen the row is inserted or updatedEach time the row is read
Disk spaceUses space, like a normal columnUses no extra space
Reading speedFast: already calculatedSlightly slower for heavy expressions
Good forValues read very often or costly to computeCheap expressions, saving space

In SQLite, VIRTUAL is the default if you write neither word.

Indexing and Write Rules

CREATE TABLE people (
  id         INTEGER PRIMARY KEY,
  first_name TEXT NOT NULL,
  last_name  TEXT NOT NULL,
  full_name  TEXT GENERATED ALWAYS AS (first_name || ' ' || last_name) VIRTUAL
);
CREATE INDEX idx_people_full_name ON people(full_name);
INSERT INTO people (first_name, last_name) VALUES ('Nusrat', 'Jahan'), ('Arif', 'Hossain');
SELECT id, full_name FROM people WHERE full_name = 'Arif Hossain';

-- You cannot write to a generated column
INSERT INTO people (first_name, last_name, full_name) VALUES ('Mitu', 'Akter', 'M. Akter'); -- fails

Output

+----+--------------+
| id | full_name    |
+----+--------------+
| 2  | Arif Hossain |
+----+--------------+
(1 row)

Error: cannot INSERT into generated column "full_name"
  • You can build an index on a generated column, even a virtual one. Searching for full_name = 'Arif Hossain' can then use the index instead of joining text for every row.
  • You cannot insert or update a generated column directly. The database rejects it, as the error shows.
  • The expression may use only columns from the same row and functions that always give the same answer for the same input. Functions such as random() or the current time are not allowed, and subqueries are not allowed.

Other Databases

DatabaseSyntax
SQLite 3.31+... GENERATED ALWAYS AS (expr) STORED | VIRTUAL
MySQL 5.7+... GENERATED ALWAYS AS (expr) STORED | VIRTUAL
PostgreSQL 12+... GENERATED ALWAYS AS (expr) STORED (virtual added in version 18)
SQL Serverline_total AS (unit_price * qty) PERSISTED (a “computed column”)

Common Mistakes

  1. Storing a calculated value in a normal column. It can drift out of date. Generate it instead.
  2. Trying to write to a generated column. Change the source columns; the generated value follows.
  3. Using the current date in the expression. “Age” cannot be a generated column, because it changes every day. Calculate it in the query.
  4. Making everything STORED. For cheap expressions, VIRTUAL saves space.

Practice Exercises

Exercise 1. Add a generated column discounted to a products table that is price minus 10%.

Show answer
CREATE TABLE products (
  id         INTEGER PRIMARY KEY,
  price      INTEGER NOT NULL,
  discounted REAL GENERATED ALWAYS AS (price * 0.9) VIRTUAL
);

Exercise 2. Why can’t a student’s current age be a generated column, while their birth year can?

Show answer

Age depends on today’s date, which keeps changing, so the expression would not be deterministic. Birth year, such as substr(born, 1, 4), depends only on the stored birth date.

Frequently Asked Questions

What is a generated column in SQL?

It is a column whose value is calculated automatically from other columns in the same row, using an expression such as unit_price times qty. You never write it directly, so it always stays consistent with its source columns.

What is the difference between STORED and VIRTUAL generated columns?

A STORED column is calculated when the row is written and saved on disk, so reads are fast. A VIRTUAL column is calculated each time it is read, so it takes no extra space.

Summary

  • GENERATED ALWAYS AS (expr) makes the database calculate a column.
  • STORED saves the value; VIRTUAL computes it on read.
  • Generated columns can be indexed but not written directly.
  • The expression must be deterministic and use only the same row.

Next: SQL CREATE TABLE AS SELECT and Temporary Tables.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *