SQL reference (MySQL and MariaDB dialects)

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#

SQL
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_name

Remarks#

  • 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 and DROP INDEX use 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 are varchar, 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 of SHOW CREATE TABLE and information_schema.COLUMNS. SHOW CREATE TABLE prints KEY k (((a * 2)),b); SHOW INDEX prints Column_name NULL and the expression in Expression.
  • DROP INDEX drops the hidden columns too. LIKE and AS SELECT carry functional indexes.
  • SHOW CREATE TABLE and SHOW INDEX list 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 CAST here (MySQL requires one).

Examples#

Example:

SQL
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;

See also#