# MySQL Generated Columns: VIRTUAL vs STORED, and Which One to Index

> Make a MySQL generated column `VIRTUAL` unless it has to be a primary key, a foreign key, or carry a `FULLTEXT` or `SPATIAL` index, which only `STORED` allows. Adding a `VIRTUAL` column to 1,000,000 rows was instant and an index on it worked as well as one on a `STORED` column, while adding the `STORED` one copied the table for 4.8 seconds with writes blocked. The trap is changing a `VIRTUAL` column's expression: `MODIFY` copies the table too, and dropping and re-adding an unindexed column does not.

Source: https://schemity.com/blog/mysql-generated-column-virtual-vs-stored/

A MySQL generated column should be `VIRTUAL` unless you need it as a primary key, a foreign key, or under a `FULLTEXT` or `SPATIAL` index, because a `VIRTUAL` column costs nothing to add, takes no space in the row, and can still be indexed. `STORED` buys cheaper reads of the unindexed value and those key and index types, and you pay for it with a full table copy when the column is added and again whenever its expression changes.

Everything below ran on MySQL 8.4.11 in a throwaway container with default settings, on this table holding 1,000,000 rows (99 MB of data, 40 MB of indexes):

```sql
CREATE TABLE order_lines (
  id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
  order_id bigint NOT NULL,
  unit_price decimal(10,2) NOT NULL,
  quantity int NOT NULL,
  attrs json NOT NULL,
  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY order_lines_order_id_idx (order_id)
);
```

## MySQL generated column virtual vs stored: what is the difference?

A `VIRTUAL` column is computed when a row is read and a `STORED` column is computed when a row is written and kept in the row.

`VIRTUAL` is what you get when you write neither keyword. The [MySQL manual](https://dev.mysql.com/doc/refman/8.4/en/create-table-generated-columns.html) says "The default is `VIRTUAL` if neither keyword is specified" and "`InnoDB` supports secondary indexes on virtual columns". The rest of this table is measured:

| | `VIRTUAL` | `STORED` |
|---|---|---|
| Add to 1,000,000 rows | Instant (`ALGORITHM=INSTANT` accepted) | 4.8 s table copy, writes blocked |
| Space in the table | None | 7.3 MB for a `decimal(12,2)` |
| `SUM()` over all rows, no index | 0.66 s | 0.36 s |
| Secondary or `UNIQUE` index | Yes | Yes |
| Primary key | Refused, error 3106 | Yes |
| `FULLTEXT` or `SPATIAL` index | Refused, error 3106 | Yes |
| Foreign key on it, or to it | Refused, error 3733 | Yes; as the child column, no `ON UPDATE CASCADE` or `SET NULL` and no `ON DELETE SET NULL` |
| Foreign key on a column it reads | Any action | No `CASCADE` or `SET NULL` action (error 1215) |
| Change the expression | Table copy with `MODIFY` | Table copy |
| Switch to the other kind | Refused, error 3106 | Refused, error 3106 |

Both kinds share the rules about what the expression may contain. `NOW()` is refused (error 3763, "contains a disallowed function"), a generated column may only refer to generated columns defined before it (error 3107), an `INSERT` may only give it `DEFAULT` (error 3105), and a column it reads cannot be dropped (error 3108).

## What does adding each kind cost on a large table?

Adding a `VIRTUAL` column changes only metadata, and adding a `STORED` column copies every row while writes wait.

```sql
ALTER TABLE order_lines
  ADD COLUMN line_total decimal(12,2)
  GENERATED ALWAYS AS (unit_price * quantity) VIRTUAL, ALGORITHM=INSTANT;
-- Query OK, 0 rows affected (0.01 sec)

ALTER TABLE order_lines
  ADD COLUMN line_total_stored decimal(12,2)
  GENERATED ALWAYS AS (unit_price * quantity) STORED;
-- Query OK, 1000000 rows affected (4.76 sec)
```

MySQL would not do the `STORED` add any cheaper way. `ALGORITHM=INSTANT` and `ALGORITHM=INPLACE` were both refused with error 1845, and `ALGORITHM=COPY, LOCK=NONE` with error 1846: "COPY algorithm requires a lock. Try LOCK=SHARED." So for those 4.8 seconds the table can be read and not written, and the time grows with the table. That is the same lock class as the changes in [does MySQL ALTER TABLE lock the table](https://schemity.com/blog/mysql-alter-table-lock-instant-inplace-copy/).

The table's data grew from 99.2 MB to 106.6 MB for the `STORED` column and did not change for the `VIRTUAL` one.

## Can you index a virtual generated column?

Yes, and the index is as large and as usable as one on a `STORED` column, because an index always stores the value.

```sql
ALTER TABLE order_lines ADD INDEX lt_v_idx (line_total), ALGORITHM=INPLACE, LOCK=NONE;        -- 1.70 s
ALTER TABLE order_lines ADD INDEX lt_s_idx (line_total_stored), ALGORITHM=INPLACE, LOCK=NONE; -- 1.52 s
```

Each index added about 24.7 MB. With the indexes in place the two columns read alike: `SUM()` took 0.23 s on the `VIRTUAL` column and 0.20 s on the `STORED` one, both from the index. Writes cost the same too. Inserting 1,000,000 rows took 3.06 s with no generated column, 3.30 s with a `VIRTUAL` one, 3.10 s with a `STORED` one, and 5.60 s and 5.29 s once each was indexed.

The optimizer also matches the expression itself. This query never names the column and still used its index:

```sql
EXPLAIN SELECT count(*) FROM order_lines WHERE unit_price * quantity = 45.00;
-- type: ref, key: lt_v_idx, rows: 155
```

The manual's condition is that "the expression must be identical and it must have the same result type", and it means it: the same query written with `quantity * unit_price` scanned all 1,000,000 rows, and so did `unit_price * quantity = 45`. The literal has to be a decimal, as in `45.00`.

This is the standard way to index one field of a JSON document:

```sql
ALTER TABLE order_lines
  ADD COLUMN sku varchar(20) COLLATE utf8mb4_bin
  GENERATED ALWAYS AS (attrs->>'$.sku') VIRTUAL, ALGORITHM=INSTANT;
ALTER TABLE order_lines
  ADD INDEX order_lines_sku_idx (sku), ALGORITHM=INPLACE, LOCK=NONE;
```

A lookup by `attrs->>'$.sku'` went from 0.41 s scanning the table to under 0.01 s, and again the query can keep using the JSON expression.

Two details in that statement matter. The `COLLATE utf8mb4_bin` matches what the JSON expression returns. Without it the column takes the table's case-insensitive collation, and once the index existed `WHERE attrs->>'$.sku' = 'sku-1'` returned 50 rows where the same query without the index returned 0: adding the index changed the answer. And the column and the index are two statements, because the two in one `ALTER TABLE` were refused `LOCK=NONE` (error 1846) and built the index with writes waiting.

A functional index, `ADD INDEX ((CAST(attrs->>'$.color' AS CHAR(10))))`, is the same thing with the `VIRTUAL` column hidden from you, and a query has to repeat the `CAST` exactly to use it.

## When does a generated column have to be STORED?

Only when it must be a primary key, take part in a foreign key, or carry a `FULLTEXT` or `SPATIAL` index.

```sql
CREATE TABLE t (a int NOT NULL, b int GENERATED ALWAYS AS (a + 1) VIRTUAL NOT NULL, PRIMARY KEY (b));
-- ERROR 3106: 'Defining a virtual generated column as primary key' is not supported for generated columns.

CREATE TABLE child (a int, pid int GENERATED ALWAYS AS (a) VIRTUAL, FOREIGN KEY (pid) REFERENCES parent (id));
-- ERROR 3733: Foreign key 'child_ibfk_1' uses virtual column 'pid' which is not supported.
```

A `STORED` column works in both places, with limits. As the child column of a foreign key it was refused `ON DELETE SET NULL` and `ON UPDATE CASCADE` (error 3104), since MySQL cannot write into a generated column. A foreign key cannot point at a `VIRTUAL` column either, even one with a `UNIQUE` index (error 3733). A `FULLTEXT` or `SPATIAL` index on a `VIRTUAL` column is refused with error 3106.

A `STORED` column also costs something a `VIRTUAL` one does not. A foreign key on a plain column that a `STORED` column reads was refused `ON UPDATE CASCADE` and `ON DELETE SET NULL` (error 1215, "Cannot add foreign key constraint"), and the same table with the column `VIRTUAL` accepted both.

The other reason to store is a value that is expensive to compute and read far more often than it is written, without an index. For plain arithmetic the read gap above was 0.66 s against 0.36 s per million rows, and an index removes it.

## What happens when you change a generated column later?

Changing the expression copies the table for both kinds, and the kind itself cannot be changed at all.

This is the surprise in the `VIRTUAL` column. Nothing is stored, and `MODIFY` still rewrote every row:

```sql
ALTER TABLE order_lines MODIFY line_total decimal(12,2)
  GENERATED ALWAYS AS (unit_price * quantity + 3) VIRTUAL;
-- Query OK, 1000000 rows affected (3.55 sec)
```

`ALGORITHM=INSTANT` and `ALGORITHM=INPLACE` were both refused for it (error 1845). Dropping the column and adding it back in one statement does the same job without the copy:

```sql
ALTER TABLE order_lines
  DROP COLUMN line_total,
  ADD COLUMN line_total decimal(12,2) GENERATED ALWAYS AS (unit_price * quantity + 3) VIRTUAL,
  ALGORITHM=INPLACE, LOCK=NONE;
-- Query OK, 0 rows affected (0.01 sec)
```

That moves the column to the end of the table unless you add `AFTER`, and it only works while the column has no index. With an index on it, the same statement was refused with error 1846 ("INPLACE ADD or DROP of virtual columns cannot be combined with other ALTER TABLE actions"), and without the `ALGORITHM` clause MySQL fell back to copying the table, as `MODIFY` does (9.2 s with the index in place). The way through is three statements, each `ALGORITHM=INPLACE, LOCK=NONE`: drop the index, drop and re-add the column, add the index again (1.9 s), with queries on that column unindexed in between.

Switching kind is refused in both directions:

```sql
ALTER TABLE order_lines MODIFY line_total decimal(12,2)
  GENERATED ALWAYS AS (unit_price * quantity) STORED;
-- ERROR 3106: 'Changing the STORED status' is not supported for generated columns.
```

`MODIFY` cannot switch kind, but a drop and re-add in one statement can. `STORED` to `VIRTUAL` took 0.02 s, and `VIRTUAL` to `STORED` costs one table copy, the same copy you would have paid on day one. That is the reason to default to `VIRTUAL`.

## Is NOT NULL checked on a virtual generated column?

Not for rows that already exist: MySQL added a `NOT NULL` `VIRTUAL` column over a row where the expression is `NULL`, and that row then reads as 0.

```sql
CREATE TABLE t (a int NULL);
INSERT INTO t VALUES (NULL), (1);
ALTER TABLE t ADD COLUMN b int GENERATED ALWAYS AS (a + 1) VIRTUAL NOT NULL;
-- Query OK, 0 rows affected, no warning

SELECT a, b, b IS NULL FROM t;
-- NULL | 0 | 0
--    1 | 2 | 0
```

New writes are checked: `INSERT INTO t (a) VALUES (NULL)` failed with error 1048, "Column 'b' cannot be null". The old row surfaces later: adding an index on `b` failed with the same error 1048, and so does any later `ALTER TABLE` that copies the table. Adding the column `WITH VALIDATION` checks the existing rows up front and was refused here with 1048. The `STORED` version of the column was refused at the `ALTER TABLE`, because the copy evaluates every row. This ran in the default strict SQL mode.

## How does Schemity handle generated columns on MySQL?

Schemity reads both kinds from the live database, shows which is which, and reports the table copy before a change runs.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. On the canvas a generated column carries its expression after an equals sign, where a default would be, and the field's details say `Generated (virtual)` or `Generated (stored)`. The expression belongs to the database, so the field form leaves only the name and description editable, which is how you [design the next one](https://schemity.com/doc/tables-and-fields/) without a diagram that disagrees with the server.

![Schemity reading order_lines from MySQL 9.7.4: line_total and line_total_stored are DECIMAL(12,2) columns drawn with "= `unit_price` * `quantity`", and sku is a VARCHAR(20) drawn with "= json_unquote(json_extr...". The line_total row is selected and the field details panel shows Nullable ticked, type DECIMAL(12,2) and Generated (virtual) with the expression `unit_price` * `quantity`.](https://schemity.com/images/blog/mysql-generated-column-virtual-vs-stored/canvas-order-lines-generated.webp)

When an AI agent edits the diagram over the [MCP server](https://schemity.com/doc/ai-assisted-design/), a switch between `VIRTUAL` and `STORED` is refused with MySQL's own reason, error 3106, and the advice to delete and re-create the column. A changed expression is planned as `MODIFY COLUMN`, and [impact analysis](https://schemity.com/doc/impact-analysis/) (Schemity Pro) reports it for what it is on this table: a rewrite of about 1,000,000 rows that holds back writes. A new `STORED` column is reported the same way, and a new `VIRTUAL` one produces no finding.

![Schemity's change preview for a migration file on MySQL 9.7.4: the planned statement ALTER TABLE order_lines ADD COLUMN color varchar(10) GENERATED ALWAYS AS (json_unquote(json_extract(attrs, '$.color'))) STORED, the new color column highlighted green on order_lines, and two impact findings: "Rewrites order_lines to change color: ~994.9K rows, 167 MB on disk" and "Filling color for every row holds back writes to order_lines while it reads ~994.9K rows, 167 MB on disk".](https://schemity.com/images/blog/mysql-generated-column-virtual-vs-stored/impact-add-stored-column.webp)

The same question on PostgreSQL, where the alternative is a trigger, is measured in [generated column vs trigger](https://schemity.com/blog/postgres-generated-column-vs-trigger/), and what a rename does to an expression that reads the column is in [renaming a column: what breaks](https://schemity.com/blog/rename-column-what-breaks-postgres-mysql-sql-server-sqlite/).

## Frequently asked questions

### Can you index a virtual generated column in MySQL?

Yes. InnoDB supports secondary indexes on `VIRTUAL` generated columns, including `UNIQUE` ones, and the index stores the computed values. On MySQL 8.4.11 the index on a `VIRTUAL` column was the same size as the one on a `STORED` column and was built with `ALGORITHM=INPLACE, LOCK=NONE`. Only a primary key, a foreign key and a `FULLTEXT` or `SPATIAL` index need the column to be `STORED`.

### Can you change a generated column from VIRTUAL to STORED in MySQL?

Not in place. `ALTER TABLE ... MODIFY` is refused with error 3106, `'Changing the STORED status' is not supported for generated columns`, in both directions. Drop the column and add it again with the other keyword, in one `ALTER TABLE` so nothing reads the table without it: `STORED` to `VIRTUAL` took 0.02 s on 1,000,000 rows, and `VIRTUAL` to `STORED` copies the table once.

### Does a MySQL generated column take disk space?

A `STORED` column does and a `VIRTUAL` column does not. On 1,000,000 rows a `STORED` `decimal(12,2)` added 7.3 MB of table data and a `VIRTUAL` one added nothing. An index on either adds the same amount, because the index holds the computed value in both cases.
