Design Indexes Around Queries
🎯 Introduction
By the end of this article, you will be able to index common filters and sort orders and evaluate maintenance costs.
🔎 Indexes narrow the search
A query should return the same users before and after adding an index; the index improves how those users are found. For example, finding Xiao Ming by name may require checking every row without a name index. With a suitable index, the database can locate matching names while examining less unrelated data.
This article uses the following original query_user dataset. See Query practice data for the creation and insertion statements:
| id | username | age | city | created_at |
|---|---|---|---|---|
| 1 | Xiao Ming | 25 | Beijing | 2026-10-01 09:00:00 |
| 2 | Xiao Hong | 30 | Shanghai | 2026-10-02 09:00:00 |
| 3 | Xiao Gang | 22 | Beijing | 2026-10-03 09:00:00 |
| 4 | Xiao Lin | 30 | Shanghai | 2026-10-04 09:00:00 |
| 5 | Xiao An | NULL | Hangzhou | 2026-10-05 09:00:00 |
We will query the same user throughout, first examining the search without a name index, then comparing it after creating one. Five rows may show no noticeable timing difference, so also inspect the database's access method.
🔍 Which records are checked without a name index?
Before creating a name index, query Xiao Ming:
SELECT id, username FROM query_user WHERE username = 'Xiao Ming';
Query result:
| id | username |
|---|---|
| 1 | Xiao Ming |
The table currently has only its primary key index on id. That helps find a user by id, but we supplied a name and do not know Xiao Ming's id. Without a suitable name index, the database must examine the table's records: a full table scan.
The following illustrates checking each row; it does not guarantee a fixed scan order:
| Record checked | Does the name equal “Xiao Ming”? | Included in result? |
|---|---|---|
| 1, Xiao Ming | Yes | Included |
| 2, Xiao Hong | No | Excluded |
| 3, Xiao Gang | No | Excluded |
| 4, Xiao Lin | No | Excluded |
| 5, Xiao An | No | Excluded |
Although only one row is returned, all five must be checked. Finding Xiao Ming does not let the scan stop: there is no unique constraint on names, so another Xiao Ming could appear later.
First, record the query plan: the search method the database intends to use.
EXPLAIN SELECT id, username FROM query_user WHERE username = 'Xiao Ming';
EXPLAIN returns plan information, not user data. When a full table scan is chosen without a name index, two key fields are:
| type | key |
|---|---|
| ALL | NULL |
ALL denotes a full table scan; a NULL key means no index was selected. Returning one row does not mean only one row was examined.
🛠 Index a common name lookup
CREATE INDEX idx_query_username ON query_user (username);
idx_query_username is the index name. After creating it, you do not need to specify this name manually in an ordinary query:
SELECT id, username FROM query_user WHERE username = 'Xiao Ming';
Query result:
| id | username |
|---|---|
| 1 | Xiao Ming |
The result is still Xiao Ming. Creating the index adds a structure ordered by name that supports searching through progressively narrower ranges. The next section explains why this can reduce the records examined.
🧱 Why indexes can skip unrelated records
An index orders values in advance and records the ranges and locations of its parts. Checking those ranges tells the database where to search.
Consider finding users aged 25. Without an age index, each user's age must be checked. With an age index, think of the search like this:
Inspect the index's range directory first
├─ Under 25 → Skip
├─ 25 to under 30 → Search here for age 25
└─ 30 and over → Skip
This simplified illustration shows only supplied ages. It does not mean the five practice rows are actually divided into three blocks.
Why can ranges be skipped? The index is already ordered by age: the under-25 range cannot contain 25, and neither can the 30-and-over range. The database only needs to enter the middle range and find all records aged 25.
If that range is still large, finer range directories can narrow the search further. Indexes improve performance by avoiding checks of many records that cannot match.
The name index works the same way: it orders names and records ranges, then follows the range containing “Xiao Ming”. The database builds and maintains this directory automatically. You write the same SELECT without implementing the search yourself.
🔍 Check whether the query uses the name index
Inspect the same query's plan again:
EXPLAIN SELECT id, username FROM query_user WHERE username = 'Xiao Ming';
If the database chooses the name index, the key fields typically look like this. This illustrates that access method rather than guaranteeing an identical plan on every machine:
| type | key |
|---|---|
| ref | idx_query_username |
ref means matching rows are found using an index value; key identifies the new name index. If ALL and NULL still appear, the index was not selected, so you cannot claim that the scan was reduced.
| Comparison | Full table scan without a name index | Lookup using the name index |
|---|---|---|
| Returned data | Xiao Ming | Xiao Ming |
| Search process | Check each row's name to find all matches | Locate the entries for “Xiao Ming” in the index first |
| As unrelated users increase | More unrelated records must be checked | Many unrelated records can usually be skipped |
An index lowers the cost of finding results rather than changing the answer. With little data or a query returning most records, an index may offer little benefit while still consuming storage and requiring maintenance on writes.
Inspect the new index
List existing indexes:
SHOW INDEX FROM query_user;
After following this article so far, the relevant index-name and column fields are shown below; other output columns are omitted:
| Key_name | Non_unique | Seq_in_index | Column_name |
|---|---|---|---|
| PRIMARY | 0 | 1 | id |
| idx_query_username | 1 | 1 | username |
Non_unique is 0 when duplicates are prohibited and 1 when allowed. Seq_in_index is the column's position within the index.
Key_name includes PRIMARY and the new index. The primary key already has an index; do not create an identical index on id.
🧩 Use composite indexes for combined queries
If an API often filters by city and then sorts by age, create:
CREATE INDEX idx_query_city_age ON query_user (city, age);
A composite index organizes multiple columns in order: first city, then age within each city. The corresponding query is:
SELECT id, city, age FROM query_user
WHERE city = 'Beijing' AND age >= 23 ORDER BY age;
Query result:
| id | city | age |
|---|---|---|
| 1 | Beijing | 25 |
This returns Xiao Ming's ID, city, and age. Once city is fixed, the age range and order can be used within that city.
Column order matters: filtering by city, or by city and age, follows the index's leftmost organization. Filtering only by age cannot locate a city range in the same way. This does not mean no index can ever be used; inspect the actual plan.
The order of conditions written in WHERE need not match the index column order. What matters is which columns participate in filtering.
📄 Covering indexes avoid fetching unnecessary full records
An ordinary InnoDB index stores the primary key of each corresponding record alongside its indexed columns. If a query needs a column absent from the index, the database uses that primary key to fetch the full record: a clustered index lookup.
The previous query reads only id, city, and age, all contained in the composite index. When the index supplies every required column without fetching full records, it is a covering index for that query.
Adding username to the query may require fetching the name by primary key because it is absent from the composite index. Query only the columns you need before deciding whether extending an index is worthwhile. Do not add every column merely to cover all queries.
🔤 Prefix searches differ from substring searches
SELECT id, username FROM query_user WHERE username LIKE 'Xiao%';
Query result:
| id | username |
|---|---|
| 1 | Xiao Ming |
| 2 | Xiao Hong |
| 3 | Xiao Gang |
| 4 | Xiao Lin |
| 5 | Xiao An |
A known prefix may let the database narrow the range using an ordinary index. However, every example name shares the same prefix, so the filter is weak and is not guaranteed to be cheaper than scanning.
A substring search with % on both sides has no fixed prefix and usually cannot locate a small index range like a prefix search. It may still scan an index, so saying it cannot use any index is inaccurate.
⚖️ Every index needs maintenance
Inserting, deleting, or updating indexed columns requires maintaining the relevant indexes. Indexes also consume disk and cache space. Prioritize frequent, expensive queries whose candidate rows can be substantially reduced.
Do not dismiss an index solely because a column has few distinct values. An index may still help if a frequently queried status occurs in only a small fraction of records. Consider the actual data distribution.
Drop an index only after confirming that it is no longer needed:
DROP INDEX idx_query_username ON query_user;
This removes a search structure without deleting user data. The next article's execution-plan exercises use the retained idx_query_city_age index.
❓ Questions and Answers
Q1: How does a unique constraint differ from an ordinary index?
A unique constraint also rejects duplicate values and is backed by a unique index. An ordinary index supplies a search structure without prohibiting duplicates.
Q2: Why did the query plan stay the same after creating an index?
For a small table, a condition matching most records, or a query unsuited to that index, the database may estimate that scanning is cheaper.
Q3: Are wider composite indexes better?
No. Wider indexes consume more space and increase write costs. Design them for specific queries.
🧪 Exercise
Keep the composite index on city and age. Write queries filtering by city, by city and age, and by age alone. In the next article, inspect their execution plans without assuming the outcome in advance.
-- Write your SQL or record your verification results here
