Indexing in MySQL

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

An index is the main lever for making a query fast, and in InnoDB the way tables are indexed also decides how rows are physically stored. This page explains the InnoDB index model, then works through each kind of index on a table of 300,000 generated rows, reading the EXPLAIN output to see what the optimizer does. Plans are explained in depth on Query Planning & EXPLAIN; the engine-agnostic indexing ideas are in Diagnosing Slow Queries. All results come from MySQL 26.10.0.

How InnoDB indexes work

Every InnoDB index is a B+tree. There are two kinds:

  • The clustered index is the table itself: a B+tree ordered by the primary key whose leaf pages hold the whole rows.

  • A secondary index is a separate B+tree ordered by the indexed columns. Each leaf entry holds the indexed columns and the primary key of the row it points to.

flowchart LR Q["WHERE customer_id = 42"] --> SI["Secondary index idx_customer: (customer_id, id)"] SI -->|"primary key values"| CI["Clustered index: leaf pages hold full rows"] CI --> ROW["Row"] Q2["WHERE id = 7"] --> CI

Two consequences drive almost every indexing decision:

  1. A secondary-index lookup that needs columns not stored in the index takes two tree descents: one in the secondary index and one in the clustered index (the "bookmark lookup"). An index that already holds every column the query needs avoids the second descent: a covering index.

  2. Every secondary index contains the primary key, so a long primary key makes every index bigger.

The architecture of pages and the buffer pool is on Architecture.

The test table

A recursive CTE generates the volume. MySQL caps recursion at cte_max_recursion_depth (1000), so raise it for the session first:

CREATE TABLE lab.big_orders (
  id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
  customer_id int NOT NULL,
  status varchar(10) NOT NULL,
  amount decimal(10,2) NOT NULL,
  created_at datetime NOT NULL,
  note varchar(60) NOT NULL
) ENGINE=InnoDB;

SET SESSION cte_max_recursion_depth = 1000000;
INSERT INTO lab.big_orders (customer_id, status, amount, created_at, note)
WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 300000)
SELECT 1 + (n * 7919) % 5000,
       ELT(1 + n % 3, 'open', 'shipped', 'cancelled'),
       ROUND(5 + (n * 31) % 49500 / 100, 2),
       TIMESTAMP('2025-01-01') + INTERVAL (n * 97) % 31536000 SECOND,
       CONCAT('order note ', n)
FROM seq;
ANALYZE TABLE lab.big_orders;
SELECT COUNT(*), MIN(created_at), MAX(created_at), COUNT(DISTINCT customer_id) FROM lab.big_orders;
+----------------+---------+----------+----------+
| Table          | Op      | Msg_type | Msg_text |
+----------------+---------+----------+----------+
| lab.big_orders | analyze | status   | OK       |
+----------------+---------+----------+----------+
+----------+---------------------+---------------------+-----------------------------+
| COUNT(*) | MIN(created_at)     | MAX(created_at)     | COUNT(DISTINCT customer_id) |
+----------+---------------------+---------------------+-----------------------------+
|   300000 | 2025-01-01 00:01:37 | 2025-12-03 19:20:00 |                        5000 |
+----------+---------------------+---------------------+-----------------------------+

300,000 orders spread over 5000 customers (60 orders each), three statuses and one year. The load took about half a second. The next examples run SET explain_format = TRADITIONAL first: the server used here defaults explain_format to TREE, so a bare EXPLAIN prints a tree rather than the table with type, key, rows and Extra columns.

A first index

Without an index on customer_id, EXPLAIN reports a full table scan (type = ALL) reading about 299,000 rows; EXPLAIN ANALYZE executes the statement and adds the real figures:

SET explain_format = TRADITIONAL;
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42;
EXPLAIN ANALYZE FORMAT=TREE SELECT * FROM big_orders WHERE customer_id = 42;
+----+-------------+------------+------------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+------------+------------+------+---------------+------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 299094 |    10.00 | Using where |
+----+-------------+------------+------------+------+---------------+------+---------+------+--------+----------+-------------+
-> Filter: (big_orders.customer_id = 42)  (cost=30238 rows=29909) (actual time=1.18..46.9 rows=60 loops=1)
    -> Table scan on big_orders  (cost=30238 rows=299094) (actual time=0.0736..38.3 rows=300000 loops=1)

The scan read 300,000 rows (about 38 ms) to return 60. Add the index and look again:

CREATE INDEX idx_customer ON big_orders (customer_id);
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42;
EXPLAIN ANALYZE FORMAT=TREE SELECT * FROM big_orders WHERE customer_id = 42;
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys | key          | key_len | ref   | rows | filtered | Extra |
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer  | idx_customer | 4       | const |   60 |   100.00 | NULL  |
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------+
-> Index lookup on big_orders using idx_customer (customer_id = 42)  (cost=21 rows=60) (actual time=0.0196..0.0718 rows=60 loops=1)

type changed from ALL to ref, the estimated rows from 299,094 to 60 and the actual time from tens of milliseconds to 0.07 ms.

Choosing the primary key

Because the primary key is the clustered key and is copied into every secondary index, it should be short, stable and, ideally, monotonically increasing:

  • Short. A BIGINT is 8 bytes; a 36-character UUID string is 36. Every secondary index entry repeats it.

  • Increasing. New rows with ascending keys are appended to the right-most leaf page, which fills completely and is then followed by a new page. Random keys land anywhere in the tree, splitting pages that are already full, leaving half-empty pages and forcing far more of the tree through the buffer pool.

  • Stable. Updating a primary key moves the row and rewrites the entries in every secondary index.

If you must expose opaque identifiers, MySQL has helpers: UUID_TO_BIN(uuid, 1) stores a UUID as 16 bytes and with the second argument swaps the time-low and time-high fields so that MySQL’s version-1 UUIDs sort roughly in time order. A measurement on the test server: 500,000 rows with a 100-character payload inserted into three tables that differ only in the primary key, each from a recursive CTE:

CREATE TABLE pk_auto      (id bigint AUTO_INCREMENT PRIMARY KEY, payload char(100) NOT NULL);
CREATE TABLE pk_uuid_text (id char(36) PRIMARY KEY,              payload char(100) NOT NULL);
CREATE TABLE pk_uuid_bin  (id binary(16) PRIMARY KEY,            payload char(100) NOT NULL);
-- each filled with INSERT ... WITH RECURSIVE ... 500000 rows; for the UUID tables the key expression is
--   UUID()                         (pk_uuid_text)
--   UUID_TO_BIN(UUID(), 1)         (pk_uuid_bin)
SELECT table_name, ROUND(data_length/1024/1024,1) AS data_mb FROM information_schema.tables
WHERE table_schema='lab' AND table_name LIKE 'pk\_%' ORDER BY table_name;
+--------------+---------+
| TABLE_NAME   | data_mb |
+--------------+---------+
| pk_auto      |    66.6 |
| pk_uuid_bin  |    70.6 |
| pk_uuid_text |    81.8 |
+--------------+---------+
Primary key Insert time (500,000 rows) Table size (MB) Key size

BIGINT AUTO_INCREMENT

0.86 s

66.6

8 bytes

BINARY(16) from UUID_TO_BIN(UUID(), 1)

1.32 s

70.6

16 bytes

CHAR(36) from UUID()

1.59 s

81.8

36 bytes

The auto-increment table was the fastest and the smallest. The differences are modest here because each table (66-82 MB) fits mostly within the 128 MiB buffer pool and the run was a single measurement on one machine. The gap grows once the index no longer fits in memory, because random inserts then cost a disk read per insert. Treat the numbers as a direction, not as a benchmark. The practical rules: use BIGINT AUTO_INCREMENT unless there is a reason not to; if you need UUIDs store them as BINARY(16) with UUID_TO_BIN(..., 1); never use CHAR(36) as a primary key of a large table. Note that UUID() in MySQL is a version-1 (time-based) UUID. A client-generated random (version-4) UUID would not benefit from the swap and would insert in fully random order.

Tables without an explicit primary key get a hidden 6-byte row id; always define one.

Composite indexes and the leftmost prefix

A multi-column index is sorted by the first column, then by the second within equal first values, and so on. The optimizer can use it for any query that constrains a leftmost prefix of its columns. Create one on (customer_id, status, created_at) and test five queries:

CREATE INDEX idx_cust_status_created ON big_orders (customer_id, status, created_at);
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42 AND status = 'open' ORDER BY created_at;
EXPLAIN SELECT * FROM big_orders WHERE status = 'open' AND created_at > '2025-06-01';
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42 AND created_at > '2025-06-01';
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42 ORDER BY status DESC, created_at DESC LIMIT 5;
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys                        | key                     | key_len | ref         | rows | filtered | Extra |
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------------+------+----------+-------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer,idx_cust_status_created | idx_cust_status_created | 46      | const,const |   20 |   100.00 | NULL  |
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------------+------+----------+-------+
+----+-------------+------------+------------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+------------+------------+------+---------------+------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 299094 |     3.33 | Using where |
+----+-------------+------------+------------+------+---------------+------+---------+------+--------+----------+-------------+
+----+-------------+------------+------------+------+--------------------------------------+--------------+---------+-------+------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys                        | key          | key_len | ref   | rows | filtered | Extra       |
+----+-------------+------------+------------+------+--------------------------------------+--------------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer,idx_cust_status_created | idx_customer | 4       | const |   60 |    33.33 | Using where |
+----+-------------+------------+------------+------+--------------------------------------+--------------+---------+-------+------+----------+-------------+
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------+------+----------+---------------------+
| id | select_type | table      | partitions | type | possible_keys                        | key                     | key_len | ref   | rows | filtered | Extra               |
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------+------+----------+---------------------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer,idx_cust_status_created | idx_cust_status_created | 4       | const |   60 |   100.00 | Backward index scan |
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------+------+----------+-------------+

What each plan shows:

  • Query 1 uses both leading columns (key_len 46: 4 bytes for customer_id and 42 for the varchar(10) status in utf8mb4) and returns the rows already sorted by created_at, so there is no Using filesort.

  • Query 2 omits the leading column, so the index cannot be used for seeking: full scan. This is the leftmost-prefix rule. (The filtered estimate of 3.33 is the optimizer’s guess at the combined selectivity.)

  • Query 3 can seek on customer_id only. created_at comes after the skipped status, so it cannot narrow the seek and is applied as a filter (Using where, filtered 33.33). The optimizer picked the narrower idx_customer.

  • Query 4 reads the index backwards (Backward index scan) to satisfy DESC ordering without sorting.

Guidelines for ordering columns: put columns tested with = first, then the column used for a range or ORDER BY last; among equality columns, selectivity matters less than which queries need the prefix. MySQL 8 can also use a skip scan on a composite index when the leading column has few distinct values (shown as Using index for skip scan); do not rely on it for a column with many values.

Covering indexes

When the index holds every column a query reads, MySQL answers from the index alone and Extra shows Using index. Remember that secondary indexes contain the primary key, so selecting id is already covered:

EXPLAIN SELECT id FROM big_orders WHERE customer_id = 42;
EXPLAIN SELECT customer_id, status FROM big_orders WHERE customer_id = 42;
EXPLAIN SELECT customer_id, status, created_at FROM big_orders WHERE customer_id = 42 AND status = 'open';
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys | key          | key_len | ref   | rows | filtered | Extra       |
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer  | idx_customer | 4       | const |   60 |   100.00 | Using index |
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------------+
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys | key          | key_len | ref   | rows | filtered | Extra |
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer  | idx_customer | 4       | const |   60 |   100.00 | NULL  |
+----+-------------+------------+------------+------+---------------+--------------+---------+-------+------+----------+-------+
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------------+------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys                        | key                     | key_len | ref         | rows | filtered | Extra       |
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------------+------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_customer,idx_cust_status_created | idx_cust_status_created | 46      | const,const |   20 |   100.00 | Using index |
+----+-------------+------------+------------+------+--------------------------------------+-------------------------+---------+-------------+------+----------+-------------+

The first query reads only customer_id and id, both in idx_customer: covered. The second also needs status, which that index lacks, so each row requires a clustered-index lookup (Extra empty). The third is covered by the composite index. Covering indexes are the cheapest optimisation for a hot read query, at the cost of wider indexes that slow writes; do not add a column to an index only to cover one rare query.

A Using index plan can still scan the whole index. A query that filters on a non-leading column may read every index entry (type = index) but never touch the table rows, which is far cheaper than type = ALL:

EXPLAIN SELECT id FROM big_orders WHERE DATE(created_at) = '2025-06-01';
+----+-------------+------------+------------+-------+---------------+-------------------------+---------+------+--------+----------+--------------------------+
| id | select_type | table      | partitions | type  | possible_keys | key                     | key_len | ref  | rows   | filtered | Extra                    |
+----+-------------+------------+------------+-------+---------------+-------------------------+---------+------+--------+----------+--------------------------+
|  1 | SIMPLE      | big_orders | NULL       | index | NULL          | idx_cust_status_created | 51      | NULL | 299094 |   100.00 | Using where; Using index |
+----+-------------+------------+------------+-------+---------------+-------------------------+---------+------+--------+----------+--------------------------+

Here type = index with 299,094 rows is a full scan of the (smaller) composite index, not a seek.

Prefix indexes

A prefix index (col(n)) indexes only the first n characters of a string column, which shrinks the index. It is the way to index a TEXT or very long VARCHAR column, but it can never be a covering index for that column, and a prefix that is too short is useless. Measure the selectivity of candidate lengths:

SELECT COUNT(DISTINCT LEFT(note, 12))/COUNT(*) AS s12, COUNT(DISTINCT LEFT(note, 14))/COUNT(*) AS s14,
       COUNT(DISTINCT LEFT(note, 16))/COUNT(*) AS s16, COUNT(DISTINCT note)/COUNT(*) AS sfull
FROM big_orders;
+--------+--------+--------+--------+
| s12    | s14    | s16    | sfull  |
+--------+--------+--------+--------+
| 0.0000 | 0.0033 | 0.3333 | 1.0000 |
+--------+--------+--------+--------+

Every note begins with order note and a space (11 characters) followed by a number, so a 12-character prefix has almost no selectivity (and an index created on note(12) produced a plan estimating 21,100 rows for a single value). Pick the shortest prefix whose selectivity is close to the full column’s, here 17 characters or the whole column. For a column such as an e-mail address or URL, 10-20 characters is typical.

Descending and functional indexes

MySQL 8 builds real descending index columns (col DESC). They matter when a query sorts in mixed directions, which a single ascending index cannot satisfy. With an ascending index, ORDER BY status, amount DESC needs a filesort; with (status, amount DESC) it is read in order and LIMIT 3 stops after three entries:

CREATE INDEX idx_status_amount ON big_orders (status, amount);
EXPLAIN SELECT id, status, amount FROM big_orders ORDER BY status, amount DESC LIMIT 3;
DROP INDEX idx_status_amount ON big_orders;
CREATE INDEX idx_status_amount_desc ON big_orders (status, amount DESC);
EXPLAIN SELECT id, status, amount FROM big_orders ORDER BY status, amount DESC LIMIT 3;
+----+-------------+------------+------------+-------+---------------+-------------------+---------+------+--------+----------+-----------------------------+
| id | select_type | table      | partitions | type  | possible_keys | key               | key_len | ref  | rows   | filtered | Extra                       |
+----+-------------+------------+------------+-------+---------------+-------------------+---------+------+--------+----------+-----------------------------+
|  1 | SIMPLE      | big_orders | NULL       | index | NULL          | idx_status_amount | 47      | NULL | 298834 |   100.00 | Using index; Using filesort |
+----+-------------+------------+------------+-------+---------------+-------------------+---------+------+--------+----------+-----------------------------+
+----+-------------+------------+------------+-------+---------------+------------------------+---------+------+------+----------+-------------+
| id | select_type | table      | partitions | type  | possible_keys | key                    | key_len | ref  | rows | filtered | Extra       |
+----+-------------+------------+------------+-------+---------------+------------------------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | index | NULL          | idx_status_amount_desc | 47      | NULL |    3 |   100.00 | Using index |
+----+-------------+------------+------------+-------+---------------+------------------------+---------+------+------+----------+-------------+

The estimated rows fell from 298,834 (with a sort) to 3.

A functional index indexes an expression, so a query that applies a function to a column can still use an index. Wrapping an indexed column in a function normally defeats the index; the second EXPLAIN below follows the creation of an index on DATE(created_at):

CREATE INDEX idx_created_date ON big_orders ((DATE(created_at)));
EXPLAIN SELECT id FROM big_orders WHERE DATE(created_at) = '2025-06-01';
EXPLAIN SELECT id FROM big_orders WHERE created_at >= '2025-06-01' AND created_at < '2025-06-02';
+----+-------------+------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys    | key              | key_len | ref   | rows | filtered | Extra |
+----+-------------+------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_created_date | idx_created_date | 4       | const |  891 |   100.00 | NULL  |
+----+-------------+------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
+----+-------------+------------+------------+-------+-------------------------+-------------------------+---------+------+--------+----------+--------------------------+
| id | select_type | table      | partitions | type  | possible_keys           | key                     | key_len | ref  | rows   | filtered | Extra                    |
+----+-------------+------------+------------+-------+-------------------------+-------------------------+---------+------+--------+----------+--------------------------+
|  1 | SIMPLE      | big_orders | NULL       | index | idx_cust_status_created | idx_cust_status_created | 51      | NULL | 298834 |    11.11 | Using where; Using index |
+----+-------------+------------+------------+-------+-------------------------+-------------------------+---------+------+--------+----------+--------------------------+

The first plan is a ref lookup on the expression index (estimate 891, and the actual count was 891). The second query, which does not use the expression, ignores it and scans the composite index, because created_at is not its leading column; a plain index on created_at would serve that range form. A functional index is implemented as a hidden virtual generated column, so it follows the rules of generated columns on Data Types & MySQL-specific SQL. It is the right tool when you cannot change the query; otherwise prefer rewriting the predicate as a range on the plain column.

Invisible indexes

An invisible index is maintained like any other but ignored by the optimizer. It lets you test dropping an index safely: make it invisible, watch for regressions, and either drop it or make it visible again (instant, with no rebuild).

ALTER TABLE big_orders ALTER INDEX idx_customer INVISIBLE;
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42;
ALTER TABLE big_orders ALTER INDEX idx_customer VISIBLE;
+----+-------------+------------+------------+------+-------------------------+-------------------------+---------+-------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys           | key                     | key_len | ref   | rows | filtered | Extra |
+----+-------------+------------+------------+------+-------------------------+-------------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_cust_status_created | idx_cust_status_created | 4       | const |   60 |   100.00 | NULL  |
+----+-------------+------------+------------+------+-------------------------+-------------------------+---------+-------+------+----------+-------+

With idx_customer hidden the query simply switched to the leftmost prefix of the composite index: the evidence that idx_customer is redundant (see below). SHOW INDEX reports Visible: NO, and SET SESSION optimizer_switch = 'use_invisible_indexes=on' lets a session see them for testing.

FULLTEXT indexes

A FULLTEXT index supports word-based search with MATCH(columns) AGAINST('...'), which a B-tree LIKE '%word%' cannot do efficiently. InnoDB supports it on CHAR, VARCHAR and TEXT columns.

ALTER TABLE products ADD FULLTEXT INDEX ft_products_name (name);
SELECT sku, name, MATCH(name) AGAINST ('desk') AS score
FROM products WHERE MATCH(name) AGAINST ('desk' IN NATURAL LANGUAGE MODE);
SELECT sku, name FROM products WHERE MATCH(name) AGAINST ('+desk -lamp' IN BOOLEAN MODE);
SELECT sku, name FROM products WHERE MATCH(name) AGAINST ('mon*' IN BOOLEAN MODE);
SELECT sku, name FROM products WHERE MATCH(name) AGAINST ('"office chair"' IN BOOLEAN MODE);
+-----+---------------+---------------------+
| sku | name          | score               |
+-----+---------------+---------------------+
| A-1 | Standing Desk | 0.15835624933242798 |
| B-7 | Desk Lamp     | 0.15835624933242798 |
+-----+---------------+---------------------+
+-----+---------------+
| sku | name          |
+-----+---------------+
| A-1 | Standing Desk |
+-----+---------------+
+-----+--------------+
| sku | name         |
+-----+--------------+
| C-9 | Monitor 27in |
+-----+--------------+
+-----+--------------+
| sku | name         |
+-----+--------------+
| A-2 | Office Chair |
+-----+--------------+
  • Natural language mode (the default) ranks rows by relevance and returns a score.

  • Boolean mode adds operators: +word required, -word excluded, word* prefix, "a phrase" exact phrase, >/< to weight terms.

  • The plan uses the index as a special access type, type = fulltext, with Ft_hints: sorted in Extra.

  • Words shorter than innodb_ft_min_token_size (3 on the test server) are not indexed, and a stopword list (innodb_ft_enable_stopword, on) removes very common words. A search for the three-letter word usb worked: it found USB-C Hub.

  • A multi-column index is searched with all of its columns in the same order: MATCH(name, descr) AGAINST ('desk lamp'), which scored Desk Lamp 1.294 against Standing Desk 0.317 in a test with a descr column added.

Full-text search is fine for simple keyword search inside the database. For stemming, fuzzy matching, facets and relevance tuning use a search engine; see Elasticsearch.

Spatial and hash indexes

Spatial indexes (SPATIAL INDEX) index GEOMETRY columns declared NOT NULL with an R-tree, for range and containment queries (MBRContains, ST_Within, and so on). For geographic data use a SRID 4326 column, whose points are written in (latitude, longitude) order:

CREATE TABLE places (id int auto_increment primary key, name varchar(30),
  pt point NOT NULL SRID 4326, SPATIAL INDEX sp_pt (pt));
INSERT INTO places (name, pt) VALUES ('London', ST_SRID(POINT(51.5074,-0.1278),4326)),
  ('Helsinki', ST_SRID(POINT(60.1699,24.9384),4326)), ('New York', ST_SRID(POINT(40.7128,-74.0060),4326));
SELECT name, ROUND(ST_Distance(pt, ST_SRID(POINT(48.8566, 2.3522),4326))/1000) AS km_from_paris
FROM places ORDER BY km_from_paris;
EXPLAIN SELECT name FROM places WHERE MBRContains(ST_Buffer(ST_SRID(POINT(48.8566,2.3522),4326), 1), pt);
+----------+---------------+
| name     | km_from_paris |
+----------+---------------+
| London   |           403 |
| Helsinki |          2779 |
| New York |          8494 |
+----------+---------------+
+----+-------------+--------+------------+-------+---------------+-------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type  | possible_keys | key   | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+-------+---------------+-------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | places | NULL       | range | sp_pt         | sp_pt | 34      | NULL |    3 |   100.00 | Using where |
+----+-------------+--------+------------+-------+---------------+-------+---------+------+------+----------+-------------+

The spatial index is used for the bounding-box search (type = range, key = sp_pt).

Hash indexes. InnoDB has no user-defined hash index: USING HASH on an InnoDB table is accepted with note 3502 ("This storage engine does not support the HASH index algorithm, storage engine default was used instead") and builds a B-tree. Hash indexes exist only in the MEMORY engine. The only hashing InnoDB does is the adaptive hash index, an internal in-memory structure it builds on its own (and which is off by default on the test server, see Architecture). To get hash-style equality lookups on a long column, store a hash of it in an indexed generated column and compare both the hash and the value.

Statistics, cardinality and ANALYZE TABLE

The optimizer chooses indexes from statistics. InnoDB stores them persistently in mysql.innodb_index_stats, estimated by sampling a number of index pages (innodb_stats_persistent_sample_pages, 20 by default). The Cardinality in SHOW INDEX is an estimate of the number of distinct values:

ANALYZE TABLE big_orders;
SHOW INDEX FROM big_orders;
| Key_name                | Seq_in_index | Column_name | Collation | Cardinality | Index_type | Visible |
| PRIMARY                 |            1 | id          | A         |      298150 | BTREE      | YES     |
| idx_customer            |            1 | customer_id | A         |        4989 | BTREE      | YES     |
| idx_cust_status_created |            1 | customer_id | A         |        4994 | BTREE      | YES     |
| idx_cust_status_created |            2 | status      | A         |       14926 | BTREE      | YES     |
| idx_cust_status_created |            3 | created_at  | A         |      298150 | BTREE      | YES     |
| idx_status_amount_desc  |            1 | status      | A         |           2 | BTREE      | YES     |
| idx_status_amount_desc  |            2 | amount      | D         |       49029 | BTREE      | YES     |

(Only seven of the output columns and rows of the listing are shown.) The table really has 300,000 rows, 5000 customers and three statuses, yet the estimates are 298,150 rows, 4,989 customers and 2 statuses: sampling produces approximate numbers that change slightly after every ANALYZE TABLE. Cardinality of the composite prefixes (customer_id, then customer_id,status) shows how selective each added column is, and a column with only a few values (status) is a poor index on its own.

ANALYZE TABLE refreshes the statistics (a brief metadata lock, no rebuild); InnoDB also recalculates them automatically after about 10% of a table has changed (innodb_stats_auto_recalc). Run it manually after a bulk load or when plans change for no reason. For skewed data in non-indexed columns use histograms, covered on Query Planning & EXPLAIN.

Index maintenance

  • Online DDL. Adding or dropping a secondary index can run in place without blocking reads or writes. Ask for that explicitly, so MySQL refuses instead of silently locking the table if it cannot:

    ALTER TABLE big_orders ADD INDEX idx_amount (amount), ALGORITHM=INPLACE, LOCK=NONE;
    ALTER TABLE big_orders ADD INDEX idx_created (created_at), ALGORITHM=COPY, LOCK=NONE;
    ERROR 1846 (0A000): LOCK=NONE is not supported. Reason: COPY algorithm requires a lock. Try LOCK=SHARED.

    The first statement succeeded; the second asked for the table-copying algorithm with no lock, which cannot be honoured, and was rejected.

  • Size. Indexes cost disk, memory and write time. The test table is 20.5 MB of data and 29.1 MB of indexes (information_schema.tables, data_length and index_length), so its four secondary indexes are bigger than the table.

  • OPTIMIZE TABLE. For InnoDB this rebuilds the table and its indexes (recreate + analyze) and reclaims space left by many deletes or random inserts. It is rarely needed; do not schedule it routinely.

    | lab.big_orders | optimize | note     | Table does not support optimize, doing recreate + analyze instead |
    | lab.big_orders | optimize | status   | OK                                                                |
  • Foreign keys require an index on the referencing columns and MySQL creates it for you (the fk_orders_customer index in the shop schema).

  • Redundant indexes. An index on (a) is redundant when (a, b) exists, as the invisible-index example showed.

Finding unused and redundant indexes

The sys schema (installed with the server) has views over performance_schema. Run a representative workload, then ask which indexes were never read. The views count only since the last server restart, so check them after a full business cycle:

SELECT COUNT(*) FROM big_orders WHERE customer_id = 42 AND status = 'open';
SELECT COUNT(*) FROM big_orders WHERE DATE(created_at) = '2025-06-01';
SELECT table_name, redundant_index_name, redundant_index_columns, dominant_index_name, dominant_index_columns
FROM sys.schema_redundant_indexes WHERE table_schema = 'lab';
SELECT * FROM sys.schema_unused_indexes WHERE object_schema = 'lab';
SELECT index_name, rows_selected, rows_inserted FROM sys.schema_index_statistics
WHERE table_schema = 'lab' AND table_name = 'big_orders' ORDER BY index_name;
+------------+----------------------+-------------------------+-------------------------+-------------------------------+
| table_name | redundant_index_name | redundant_index_columns | dominant_index_name     | dominant_index_columns        |
+------------+----------------------+-------------------------+-------------------------+-------------------------------+
| big_orders | idx_customer         | customer_id             | idx_cust_status_created | customer_id,status,created_at |
+------------+----------------------+-------------------------+-------------------------+-------------------------------+
+---------------+-------------+------------------------+
| object_schema | object_name | index_name             |
+---------------+-------------+------------------------+
| lab           | big_orders  | idx_customer           |
| lab           | big_orders  | idx_status_amount_desc |
| lab           | places      | sp_pt                  |
| lab           | t_gen       | domain                 |
+---------------+-------------+------------------------+
+-------------------------+---------------+---------------+
| index_name              | rows_selected | rows_inserted |
+-------------------------+---------------+---------------+
| idx_created_date        |           891 |             0 |
| idx_cust_status_created |            20 |             0 |
| idx_customer            |             0 |             0 |
| idx_status_amount_desc  |             0 |             0 |
| PRIMARY                 |             0 |             0 |
+-------------------------+---------------+---------------+

sys.schema_redundant_indexes flags idx_customer as redundant with the composite index, and schema_unused_indexes lists every index that has not been read since startup, including idx_customer and idx_status_amount_desc here. (rows_inserted is 0 only because these counters cover work since the last restart.) Combine the two views with the invisible-index technique before dropping anything: PRIMARY and unique indexes that enforce constraints never appear in schema_unused_indexes because the view leaves out indexes that enforce constraints.

Index design checklist

flowchart TD A["Slow query"] --> B["EXPLAIN: type = ALL or large rows?"] B -->|"yes"| C["Equality columns first, then range or ORDER BY column"] C --> D["Can it be covering?"] D -->|"yes, query is hot"| E["Add the selected columns"] D -->|"no"| F["Keep the index narrow"] E --> G["EXPLAIN ANALYZE, compare actual rows"] F --> G B -->|"no"| H["Check statistics: ANALYZE TABLE, histogram"]
  1. Define a short, increasing primary key.

  2. Index the columns used to find rows (WHERE equality, JOIN), then those used to sort or range.

  3. Check with EXPLAIN that key is the one you expect and Extra has no unexpected Using filesort or Using temporary.

  4. Prefer one composite index over several single-column ones; remove redundant ones after testing them invisible.

  5. Re-measure after data growth; statistics and plans change.