Functional indexes
Indexes on expressions, written as a parenthesised key part, and how they are built from hidden generated columns.
A functional index is an index on an expression, written as a parenthesised key part (D76, D77).
Syntax#
KEY name ((expr) [, ...] [, col_name ...])
UNIQUE KEY name ((expr) ...)
CREATE [UNIQUE] INDEX name ON tbl_name ((expr) [, col_name ...])
ALTER TABLE tbl_name ADD [UNIQUE] INDEX [name] ((expr) [, col_name ...])
DROP INDEX name ON tbl_nameRemarks#
- How it works. As MySQL does, an expression in a key becomes a hidden stored, invisible generated column (named
!hidden!<index>!<position>!0) and the index is made on it, so unique keys, updates andDROP INDEXuse the code every index uses. - The hidden column is typed from the expression without evaluating it (a column keeps its type; whole-number arithmetic and comparisons are
bigint; decimal and float arithmetic follow; text functions arevarchar, at least 255). - An unnamed index whose first part is an expression is called
functional_index(_2, ...). An unknown column in the expression is error 1054 (... in 'functional index'). - The hidden columns are left out of
DESCRIBE, the column list ofSHOW CREATE TABLEandinformation_schema.COLUMNS.SHOW CREATE TABLEprintsKEY k (((a * 2)),b);SHOW INDEXprintsColumn_name NULLand the expression inExpression. DROP INDEXdrops the hidden columns too.LIKEandAS SELECTcarry functional indexes.SHOW CREATE TABLEandSHOW INDEXlist unique indexes before the others, as MySQL does.- The output is identical to MySQL 9.7.
Not supported yet#
- A query that writes the expression (
WHERE a * 2 = 4) is not answered from the index; the rows are the same. - The expression is not checked for determinism.
- A column used by a functional index can be dropped, which breaks the index.
- JSON expressions need no
CASThere (MySQL requires one).
Examples#
Example:
CREATE TABLE t (id INT PRIMARY KEY, a INT, b INT, name VARCHAR(20),
KEY ka ((a * 2)), UNIQUE KEY u1 ((LOWER(name))), KEY kb (b, (a + b)), KEY ((a - b)));
INSERT INTO t VALUES (1, 1, 10, 'Ann'), (2, 2, 20, 'Bob');
INSERT INTO t VALUES (3, 3, 30, 'ann'); -- error 1062: LOWER(name) is taken
CREATE INDEX k3 ON t ((b DIV 10));
ALTER TABLE t ADD INDEX k4 ((a + 1), name);
DROP INDEX k3 ON t;