SQL reference (MySQL and MariaDB dialects)

Generated columns

GENERATED ALWAYS AS columns, VIRTUAL and STORED, when they are computed and the rules and gaps.

A generated column's value is computed from other columns of the same row (D74, D77).

Syntax#

SQL
col_name data_type [GENERATED ALWAYS] AS (expr) [VIRTUAL | STORED] [NOT NULL] [UNIQUE [KEY]] [COMMENT 'string']
ALTER TABLE tbl_name ADD COLUMN col_name data_type AS (expr) [VIRTUAL | STORED]

Arguments#

NameMeaningDefault
exprExpression over columns of the row. It may use an earlier generated column.none
VIRTUAL, STOREDBoth kinds are computed when the row is written and kept in the row; only SHOW CREATE TABLE and DESCRIBE tell them apart.VIRTUAL

Remarks#

  • Computed by INSERT, REPLACE, INSERT ... SELECT, ON DUPLICATE KEY UPDATE, every UPDATE (also over joins) and the row rewrite of ALTER TABLE (adding a generated column fills the old rows). Indexes and unique keys on a generated column work.
  • A value given to a generated column other than DEFAULT is error 3105. A NOT NULL generated column that gets NULL is 1048. A default or AUTO_INCREMENT on one is 1221. An unknown column in the expression is 1054 (... in 'generated column function').
  • SHOW CREATE TABLE prints GENERATED ALWAYS AS (<canonical expression>) VIRTUAL|STORED. DESCRIBE says VIRTUAL GENERATED or STORED GENERATED in Extra.
  • LIKE carries generated columns; AS SELECT makes plain columns, as MySQL.
  • The output is identical to MySQL 9.7.

Not supported yet#

  • Division by zero in the expression gives NULL where MySQL's strict mode refuses the statement (1365).
  • No check that the expression is deterministic or free of subqueries, nor that a column it uses is not dropped or retyped.
  • A generated column cannot be the target of a foreign key action.
  • information_schema.COLUMNS.GENERATION_EXPRESSION is not filled.

Examples#

Example:

SQL
CREATE TABLE t (id INT PRIMARY KEY, a INT, b INT,
  s INT GENERATED ALWAYS AS (a + b) STORED,
  v INT AS (a * 2) VIRTUAL,
  w BIGINT AS (s + v) NOT NULL,
  n VARCHAR(20) AS (CONCAT(a, b)),
  UNIQUE KEY ux (v));
INSERT INTO t (id, a, b) VALUES (1, 1, 2), (2, 10, 20);
INSERT INTO t VALUES (3, 5, 6, DEFAULT, DEFAULT, DEFAULT, DEFAULT);
INSERT INTO t (id, a, b, s) VALUES (4, 1, 1, 5);      -- error 3105
UPDATE t SET s = DEFAULT, b = 0 WHERE id = 2;
ALTER TABLE t5 ADD COLUMN z INT AS (x * y) STORED;

See also#