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#
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#
| Name | Meaning | Default |
|---|---|---|
expr | Expression over columns of the row. It may use an earlier generated column. | none |
VIRTUAL, STORED | Both 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, everyUPDATE(also over joins) and the row rewrite ofALTER 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
DEFAULTis error 3105. ANOT NULLgenerated column that gets NULL is 1048. A default orAUTO_INCREMENTon one is 1221. An unknown column in the expression is 1054 (... in 'generated column function'). SHOW CREATE TABLEprintsGENERATED ALWAYS AS (<canonical expression>) VIRTUAL|STORED.DESCRIBEsaysVIRTUAL GENERATEDorSTORED GENERATEDinExtra.LIKEcarries generated columns;AS SELECTmakes 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_EXPRESSIONis not filled.
Examples#
Example:
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;