Example 1
Auto-compute a line-item total from quantity and unit price
Each row is inserted with only id, qty, and unit_price. The engine computes total_price = qty * unit_price automatically: row 1 gets 3 × 10 = 30, row 2 gets 5 × 8 = 40, row 3 gets 2 × 25 = 50. The STORED keyword (or PERSISTED in SQL Server) writes this computed value to disk so it can be indexed and read without re-evaluating the expression. Attempting to set total_price explicitly in an INSERT or UPDATE would raise an error — the column is always owned by the engine. SQL Server omits the data type in the column definition because the engine infers it from the expression; all other engines require the type to be declared before GENERATED ALWAYS AS.
CREATE TABLE order_items (
id INT,
qty INT,
unit_price INT,
total_price INT GENERATED ALWAYS AS (qty * unit_price) STORED
);
INSERT INTO
order_items (id, qty, unit_price)
VALUES
(1, 3, 10),
(2, 5, 8),
(3, 2, 25);SELECT
id,
qty,
unit_price,
total_price
FROM
order_items
ORDER BY
id;| id | qty | unit_price | total_price |
|---|---|---|---|
| 1 | 3 | 10 | 30 |
| 2 | 5 | 8 | 40 |
| 3 | 2 | 25 | 50 |
CREATE TABLE order_items (
id INT,
qty INT,
unit_price INT,
total_price AS qty * unit_price PERSISTED
);
INSERT INTO
order_items (id, qty, unit_price)
VALUES
(1, 3, 10),
(2, 5, 8),
(3, 2, 25);SELECT
id,
qty,
unit_price,
total_price
FROM
order_items
ORDER BY
id;| id | qty | unit_price | total_price |
|---|---|---|---|
| 1 | 3 | 10 | 30 |
| 2 | 5 | 8 | 40 |
| 3 | 2 | 25 | 50 |
MySQL, MariaDB, PostgreSQL, and SQLite use GENERATED ALWAYS AS (expr) STORED. SQL Server uses col AS expr PERSISTED with no type declaration. Results are identical.