skip to content

In MySQL 8.4, how do prefix, descending and functional index key parts differ, and what does each restrict about the queries using it?

level: middleimportance: should knowfreq 38%

answer

  1. part of a value, reversed value, computed value
  2. characters, not bytes, for text
  3. double parentheses around the expression
  4. hidden virtual generated column

basics

~20 s

A prefix part col(N) indexes the first N characters, so it cannot cover the column or fully order it. A DESC part stores keys in descending order. A functional part ((expr)) indexes an expression, used only when the query repeats it exactly.

solid answer

~50 s

A **prefix** key part, `col(N)`, indexes only the leading N characters of a string (bytes for binary types); it is required for `TEXT` and `BLOB` and limited to 3072 bytes with the `DYNAMIC` row format. It cannot return the full value, so it cannot cover that column or fully resolve an `ORDER BY` on it, and a `UNIQUE` prefix enforces uniqueness only over the prefix. A **descending** part, `col DESC`, is stored in descending order in InnoDB, so mixed-direction sorts such as `ORDER BY a ASC, b DESC` can be read forward; it is not allowed on `HASH`, `FULLTEXT` or `SPATIAL` indexes. A **functional** part, `INDEX ((expr))`, indexes an expression through a hidden virtual generated column. The query must contain the same expression with the same arguments and collation, a primary key cannot use one, and it takes no prefix length.

code

sql · 16 lines
sql
CREATE TABLE products (
  id         BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  title      VARCHAR(500) NOT NULL,
  created_at DATETIME NOT NULL,
  rating     INT NOT NULL,
  attrs      JSON,
  KEY idx_title_prefix (title(32)),
  KEY idx_created_rating (created_at DESC, rating ASC),
  KEY idx_color ((CAST(attrs->>'$.color' AS CHAR(20)) COLLATE utf8mb4_bin))
) ENGINE=InnoDB;

-- Can use idx_color: the expression and collation match the index
EXPLAIN SELECT id FROM products WHERE attrs->>'$.color' = 'red';

-- Forward scan of idx_created_rating, no filesort
EXPLAIN SELECT id FROM products ORDER BY created_at DESC, rating ASC LIMIT 20;

go deeper

for a junior

Recall the three syntaxes: col(N) for a prefix, col DESC for descending, and an expression in its own parentheses for a functional key part.

for a middle

Explain what each stores and what each blocks: covering and sorting for prefixes, the mixed-direction use of DESC, the exact-match rule for functional parts.

for a senior

Diagnose why a functional index is ignored, including the collation mismatch between CAST and the ->> operator, and size a prefix by measuring its selectivity.

for a principal

Weigh an indexed expression against a stored generated column the team can see and query, and set conventions so applications write the expression the index expects.

## Three ways a key part can differ from a plain column MySQL's `CREATE INDEX` grammar defines a key part as `{col_name [(length)] | (expr)} [ASC | DESC]`. So besides naming a whole column, a key part can be a **prefix** of a column, an **expression**, and either kind can be stored **descending**. Each changes what the index can do. | Key part | Syntax | What is stored | Main restriction | |---|---|---|---| | Prefix | `title(32)` | the first 32 characters | cannot cover the column or fully order it | | Descending | `created_at DESC` | the value, in descending order | InnoDB B-tree indexes only | | Functional | `((UPPER(sku)))` | the expression's result | the query must repeat the expression exactly | ## Prefix key parts - **Syntax and units.** `col_name(length)` indexes the leading part of a string. The length counts **characters** for nonbinary types (`CHAR`, `VARCHAR`, `TEXT`) and **bytes** for binary types (`BINARY`, `VARBINARY`, `BLOB`), while the limits are in bytes, so a `utf8mb4` column uses up to four bytes per character. - **Limits.** Prefixes are optional for `CHAR`, `VARCHAR`, `BINARY` and `VARBINARY` and **mandatory** for `TEXT` and `BLOB`. InnoDB allows up to **3072 bytes** with the `DYNAMIC` or `COMPRESSED` row format and 767 bytes with `REDUNDANT` or `COMPACT`. - **What it cannot do.** The index does not hold the full value, so it cannot supply that column to a covering read, and it cannot fully resolve an `ORDER BY` on the column: values that agree on the first N characters are not ordered beyond them, so a filesort is needed. - **Unique prefixes.** A `UNIQUE` index with a prefix requires values to be unique **within the prefix length**, which can reject rows that differ only after it. - **Too long a prefix.** If the prefix exceeds the column's size, a nonunique index is an error in strict SQL mode and is shortened with a warning otherwise; a unique index is always an error. - `SHOW INDEX` reports the prefix in `Sub_part`; `FULLTEXT` indexes ignore any prefix you give. ## Descending key parts - `DESC` in an index definition makes InnoDB **store keys in descending order**. Older MySQL releases parsed `DESC` and ignored it, so old advice that "MySQL has no descending indexes" is out of date. - The benefit is **mixed directions**. With `INDEX (c1 ASC, c2 DESC)`, `ORDER BY c1 ASC, c2 DESC` is a forward scan with no filesort. A single-direction sort can already use an ascending index read backwards, which `EXPLAIN` shows as `Backward index scan` in `Extra`, though the manual notes a forward scan is more efficient. - Restrictions in MySQL 8.4: - descending indexes are supported for InnoDB only; - `ASC`/`DESC` are not allowed on `HASH`, `FULLTEXT`, `SPATIAL` or multi-valued indexes; - an index with descending key parts is not used for `MIN()`/`MAX()` optimisation of an aggregate query that has no `GROUP BY`; - change buffering is not supported for a secondary index with a descending key column. ## Functional key parts - **Syntax.** Wrap each expression in its own parentheses: `INDEX ((col1 + col2), (col1 - col2), col1)`. Without them the statement is an error. A functional part cannot be just a column name, and functional and plain parts can be mixed. - **Implementation.** Each functional key part is a **hidden virtual generated column** with an ordinary index on it. That has consequences: 1. It counts against the table's column limit and inherits generated-column rules: no subqueries, parameters, variables or stored functions. 2. A primary key cannot include one, since a primary key needs a stored generated column; `UNIQUE` is allowed. 3. `SPATIAL` and `FULLTEXT` indexes cannot have functional parts, and functional parts are not permitted in foreign keys. 4. Index Condition Pushdown is not supported on indexes over virtual generated columns. - **Matching rule.** The optimizer uses the index only when the query contains the **same expression**. An index on `(SUBSTRING(col1, 1, 10))` serves `WHERE SUBSTRING(col1, 1, 10) = ...` and not `SUBSTRING(col1, 1, 9)`. - **The JSON trap.** `INDEX ((data->>'$.name'))` fails: `->>` returns `LONGTEXT`, which cannot be indexed without a prefix, and functional parts take no prefix. `CAST(data->>'$.name' AS CHAR(30))` can be indexed, but `CAST` returns the server's default collation while `->>` returns `utf8mb4_bin`, so `WHERE data->>'$.name' = 'James'` does not match. Adding `COLLATE utf8mb4_bin` to the indexed expression, or repeating the full `CAST` in the query, makes the index usable. Why a function on an indexed column defeats an ordinary index is the general lesson on expression indexes; the MySQL-specific part is this syntax and the generated-column machinery behind it.

  • In MySQL with InnoDB, how would you choose N for a prefix index on a long VARCHAR column such as a URL?
    Pick the shortest prefix that is nearly as selective as the full column: compare `COUNT(DISTINCT LEFT(url, N))` with `COUNT(DISTINCT url)` for a few values of N. URLs often share a long common start such as a scheme and host, so a short prefix can be almost useless. Remember the index then cannot cover `url` or sort by it, and a unique prefix would reject URLs that differ only after N characters.
  • In MySQL 8.4, why does CREATE INDEX idx ON t ((col)) fail while CREATE INDEX idx ON t (col) works?
    A functional key part cannot consist solely of a column name; the doubled parentheses ask for an expression index, and a bare column is not one. Write a plain column key part without the extra parentheses instead. The doubled parentheses are needed only when the key part really is an expression, such as `((col1 + col2))`.

  • A prefix index can cover a SELECT of the full column
  • MySQL ignores DESC in index definitions
  • A functional index is used for any expression on that column
  • A prefix length on a utf8mb4 column always counts bytes
  • A functional key part can be part of the primary key

Assumes MySQL 8.4, where DESC key parts are stored descending and functional key parts exist; much older releases parsed DESC and ignored it.