Mastering indexing in MySQL and MariaDB: a path to optimization
An index is only useful if your queries can use it, and EXPLAIN is how you find out.
Both MySQL and MariaDB use B-tree indexes to find data quickly. A good index can turn a query that reads every row of a table into one that reads a single row, while a missing or poorly chosen index is one of the most common causes of slow queries.
This article takes a closer look at how indexing works in MySQL and MariaDB, the types of indexes you can create, how to check whether a query uses an index, and how to keep your indexes effective. All the examples were tested on MySQL 9.7 and MariaDB 12.3, the current long-term support releases, using the InnoDB storage engine, which is the default in both.
What is an index?#
When you query a table for specific rows without a suitable index, the database has to read every row and check whether it matches. This is called a full table scan, and it gets slower as the table grows.
An index is a separate data structure that keeps the values of one or more columns in sorted order, with a pointer to each matching row. Because the values are sorted, the database can jump straight to the rows it needs instead of scanning the whole table, much like you'd use the index at the back of a book instead of reading every page.
Say you want to find the customer whose first name is Ava in the following Customer table:
customer_id | first_name | last_name | email
------------+------------+-----------+--------------------------
1 | John | Doe | [email protected]
2 | Jane | Smith | [email protected]
3 | Robert | Johnson | [email protected]
4 | Emily | Williams | [email protected]
5 | Michael | Brown | [email protected]
6 | Sophia | Davis | [email protected]
7 | Daniel | Miller | [email protected]
8 | Olivia | Jones | [email protected]
9 | William | Wilson | [email protected]
10 | Ava | Moore | [email protected]Without an index on first_name, the database checks all ten rows. With one, it follows a B-tree to the right row.
How B-tree indexes work#
A B-tree index organizes the indexed values into a tree, with a root node at the top, branch nodes in the middle, and leaf nodes at the bottom. Each node tells the database which direction to go, so it can find any value in a few steps, no matter how large the table is.
This simplified diagram shows a B-tree index on the first_name column:

To find Ava, the search starts at the root node, Michael. Since Ava comes before Michael alphabetically, it goes left to Emily, then left again to Daniel, and left once more to the leaf node that holds Ava. The leaf points to Ava's row in the table.
The leaf nodes are also linked together in order, which is why indexes speed up range queries, such as names between A and D, and ORDER BY: once the database finds the first value, it reads the following leaves in sequence.
The diagram is simplified to show the idea. In InnoDB, each node is a page that holds hundreds of keys, so even a table with millions of rows needs only three or four levels.
Types of indexes#
You'll often see indexes described in different ways, such as single-level and multi-level, or clustered and non-clustered. In MySQL and MariaDB with InnoDB, the types that matter in practice are the following.
1. The primary key (clustered index)#
In InnoDB, every table is stored as a clustered index on its primary key: the table's rows live in the leaf nodes of the primary key's B-tree, sorted by the key. That makes looking up a row by its primary key very fast.
You don't create the clustered index yourself, and there's no CREATE CLUSTERED INDEX statement in MySQL or MariaDB. InnoDB always uses the primary key. If a table has no primary key, it uses the first UNIQUE index whose columns are all NOT NULL, and if there's none, it generates a hidden row ID. Because rows are stored in primary key order, a short key that always increases, like an auto-increment integer, keeps inserts efficient.
2. Secondary indexes (non-clustered)#
Every other index you create is a secondary index. It's a separate B-tree that stores the indexed column values along with the row's primary key. To fetch the full row, InnoDB finds the value in the secondary index, then looks up the row in the clustered index using that primary key.
You don't need to mark an index as non-clustered. Any index you create with CREATE INDEX is a secondary index.
3. Composite indexes#
A composite index, also called a multi-column index, covers more than one column, such as (last_name, first_name). The index is sorted by the first column, then by the second column within each value of the first, and so on.
Column order matters. A composite index can be used for queries that filter on its leftmost columns, so an index on (last_name, first_name) helps queries that filter on last_name, or on last_name and first_name, but not queries that filter only on first_name. This is called the leftmost prefix rule, and we'll see it in action below.
4. Unique indexes#
A unique index works like a secondary index but also prevents duplicate values, so it's both a constraint and a way to speed up lookups. It's a good fit for columns like email addresses or usernames.
5. Other index types#
MySQL and MariaDB also support FULLTEXT indexes for searching words in text columns, and SPATIAL indexes for geographic data. MySQL can index the result of an expression, such as LOWER(email), with a functional index. In MariaDB, you get the same effect by indexing a generated column.
How to create indexes#
Now let's create some indexes and see how the database uses them. To follow along, you need a MySQL or MariaDB database and a client, such as the mysql or mariadb command-line client or MySQL Workbench.
How to create the customer table#
-
Connect to your database and create the Customer table:
CREATE TABLE Customer ( customer_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100), phone_number VARCHAR(15), address VARCHAR(255) ); -
Insert some data:
INSERT INTO Customer (customer_id, first_name, last_name, email, phone_number, address) VALUES (1, 'John', 'Doe', '[email protected]', '123-456-7890', '123 Main St'), (2, 'Jane', 'Smith', '[email protected]', '987-654-3210', '456 Oak Ave'), (3, 'Robert', 'Johnson', '[email protected]', '111-222-3333', '789 Pine Rd'), (4, 'Emily', 'Williams', '[email protected]', '555-666-7777', '101 Cedar Ln'), (5, 'Michael', 'Brown', '[email protected]', '444-555-8888', '202 Elm St'), (6, 'Sophia', 'Davis', '[email protected]', '999-888-7777', '303 Maple Ave'), (7, 'Daniel', 'Miller', '[email protected]', '777-888-9999', '404 Birch Rd'), (8, 'Olivia', 'Jones', '[email protected]', '333-222-1111', '505 Pine St'), (9, 'William', 'Wilson', '[email protected]', '111-333-5555', '606 Oak Ln'), (10, 'Ava', 'Moore', '[email protected]', '888-777-6666', '707 Cedar Ave');
With only ten rows, the database may decide a full table scan is just as fast as using an index. To see the plans below, we added another 10,000 generated rows to the table, which is closer to a real workload.
The primary key is already indexed#
Before you add any indexes, list the ones the table already has:
SHOW INDEX FROM Customer;You'll see an index named PRIMARY on customer_id, created automatically by the PRIMARY KEY definition. This is the clustered index, so you don't need to create another index on customer_id. If you do, as in CREATE INDEX idx_customer_id ON Customer(customer_id), the database accepts it, but it's a redundant index that only slows down writes.
How to check whether a query uses an index#
The EXPLAIN statement shows how the database plans to run a query, including whether it uses an index. Here's the plan for finding a customer by email before there's an index on email, in MySQL:
EXPLAIN SELECT * FROM Customer WHERE email = '[email protected]';-> Filter: (Customer.email = '[email protected]') (cost=1014 rows=990)
-> Table scan on Customer (cost=1014 rows=9900)Table scan means MySQL reads every row to find the match. In MySQL 9.7, EXPLAIN shows this tree format by default. MariaDB, and MySQL with EXPLAIN FORMAT=TRADITIONAL, show a table instead, where type: ALL and key: NULL mean the same thing: a full table scan with no index.
Secondary indexes#
To speed up lookups by email, create an index on the email column with the CREATE INDEX statement:
CREATE INDEX idx_email ON Customer(email);Run the same EXPLAIN again:
-> Index lookup on Customer using idx_email (email = '[email protected]') (cost=0.35 rows=1)The database now reads a single row through idx_email instead of scanning about 10,000 rows. In MariaDB's output, type changes from ALL to ref, and key shows idx_email.
Since every customer should have a different email address, a unique index would be an even better fit here. It speeds up lookups the same way and also rejects duplicates:
CREATE UNIQUE INDEX idx_email_unique ON Customer(email);If you add the unique index, drop idx_email, because the two indexes now cover the same column and the plain one is redundant.
Composite indexes#
To search by full name, create a composite index on last_name and first_name:
CREATE INDEX idx_last_first ON Customer(last_name, first_name);The database uses it when the query filters on both columns:
EXPLAIN SELECT * FROM Customer WHERE last_name = 'Moore' AND first_name = 'Ava';-> Index lookup on Customer using idx_last_first (last_name = 'Moore', first_name = 'Ava') (cost=0.35 rows=1)It also uses it for last_name alone, because last_name is the first column in the index. But a query on first_name alone can't use it, and falls back to a table scan:
EXPLAIN SELECT * FROM Customer WHERE first_name = 'Ava';-> Filter: (Customer.first_name = 'Ava') (cost=1014 rows=990)
-> Table scan on Customer (cost=1014 rows=9900)That's the leftmost prefix rule. When you design a composite index, put the column your queries always filter on first. If you also need fast lookups by first_name alone, that needs its own index.
Best practices and key points#
- The primary key is your clustered index. Choose a short key that always increases, and don't create a separate index on it.
- Index columns that your queries filter, join, or sort on, especially columns with many distinct values, like email.
- Columns with only a few distinct values, like status or category, rarely benefit from an index on their own, because each value matches a large share of the table. They can still be useful as the second column of a composite index.
- Order composite index columns by how your queries use them, with the column you always filter on first.
How to optimize indexes#
Once you have indexes, a few strategies keep them working for you.
1. Use covering indexes#
A covering index contains every column a query needs, so the database can answer the query from the index alone, without reading the table rows. For example, the idx_last_first index covers this query, because it only selects the two indexed columns:
EXPLAIN SELECT first_name, last_name FROM Customer WHERE last_name = 'Moore';-> Covering index lookup on Customer using idx_last_first (last_name = 'Moore') (cost=1.06 rows=1)MySQL says Covering index lookup, and in the traditional format, the Extra column shows Using index. Selecting only the columns you need, rather than SELECT *, makes covering indexes possible.
2. Find and remove redundant and unused indexes#
Every index has to be updated on every insert, update, and delete, so indexes that don't help any query only slow down writes and use storage.
Both MySQL and MariaDB include views in the sys schema that help you find them. This query lists indexes that duplicate another index, such as a second index on the primary key column:
SELECT redundant_index_name, dominant_index_name
FROM sys.schema_redundant_indexes
WHERE table_schema = DATABASE();For the redundant idx_customer_id index mentioned earlier, it reports idx_customer_id as redundant to PRIMARY. If you created both email indexes, it also reports idx_email as redundant to idx_email_unique. Similarly, sys.schema_unused_indexes lists indexes that haven't been used since the server last started. Check it after the server has run for a while under real traffic, so that rarely used but important indexes have a chance to show up.
3. Test before you drop an index#
Dropping an index on a large table is easy, but adding it back can take a long time. Instead, you can first tell the database to ignore the index while still keeping it up to date. In MySQL, make it invisible:
ALTER TABLE Customer ALTER INDEX idx_email INVISIBLE;In MariaDB, mark it as ignored:
ALTER TABLE Customer ALTER INDEX idx_email IGNORED;Queries stop using the index right away. If nothing gets slower, drop it with DROP INDEX idx_email ON Customer;. If something does, make it visible again with VISIBLE in MySQL or NOT IGNORED in MariaDB.
4. Avoid over-indexing#
Indexes make reads faster but writes slower, and each one uses disk space and memory. Don't add an index for every column. Add indexes for the queries your application actually runs, and check with EXPLAIN that they're used.
5. Analyze query patterns#
Before creating indexes, find out which queries run most often and which ones are slow. MySQL and MariaDB can log slow queries with the slow query log, and the columns used in their WHERE, JOIN, and ORDER BY clauses are your best candidates for indexes.
Summary#
This article explored indexing in MySQL and MariaDB, from how B-tree indexes work to the types of indexes InnoDB uses: the primary key as the clustered index, secondary indexes, composite indexes, and unique indexes. You also learned how to check whether a query uses an index with EXPLAIN, and how to keep your indexes effective with covering indexes, by removing redundant ones, and by testing changes with invisible or ignored indexes.
An index is only useful if your queries can use it, and EXPLAIN is how you find out.
If you'd rather not manage database servers yourself, Sevalla's Database Hosting runs managed MySQL and MariaDB databases that you can connect to your applications over a private network, so you can focus on your schema and indexes.