MySQL query-plan reading
You can read MySQL access types and process-list state to identify scans or sorting that slow restaurant and menu queries.
Learning outcomes
- Interpret MySQL 8 EXPLAIN output, including access type, selected index, estimated rows and additional operations.
- Identify full table scans, inefficient index lookups and sorting caused by indexes that do not match query conditions.
- Design composite indexes using the B-tree leftmost-prefix rule for order history and keyset pagination.
- Use EXPLAIN ANALYZE and SHOW FULL PROCESSLIST to investigate actual query execution and database activity.
- Correlate query plans with Go connection-pool statistics to distinguish slow queries from connection saturation.
When restaurant listings or order history become slow, you need to establish whether MySQL is examining too many rows, sorting unnecessarily or waiting for an available connection. In the food-delivery backend, these problems become more visible as the orders and restaurants tables grow. You can inspect MySQL's execution plan before changing indexes or rewriting queries.
Query execution plans
EXPLAIN asks MySQL to describe how it plans to execute a SQL statement. It shows which tables are accessed, which indexes are considered and how MySQL expects to retrieve the required rows.
The order history endpoint is a useful example. It retrieves a customer's recent orders using keyset pagination.
Consider its query:
EXPLAIN
SELECT id, user_id, restaurant_id, status, total_paise, created_at
FROM orders
WHERE user_id = ?
AND (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT 21;The endpoint returns up to 20 orders. It requests 21 rows so that the additional row indicates whether another page exists.
Run the query through MySQL Workbench or the MySQL CLI with representative parameter values.
The execution plan is more useful when your database contains realistic data. An optimizer can make different decisions for a table containing ten rows and one containing hundreds of thousands of rows.
EXPLAIN output columns
A typical MySQL 8 EXPLAIN result contains several columns. Each describes a different part of the execution plan.
| Column | Meaning |
|---|---|
id | Identifies a SELECT operation within the query |
select_type | Describes the SELECT operation, such as SIMPLE or PRIMARY |
table | Identifies the table accessed at this step |
type | Describes how MySQL accesses the table |
possible_keys | Lists indexes that MySQL considers potentially useful |
key | Identifies the index MySQL actually selects |
key_len | Shows the number of bytes of the selected index key used |
ref | Shows the values or columns compared against the selected index |
rows | Estimates how many rows MySQL expects to examine |
filtered | Estimates the percentage of examined rows that pass remaining conditions |
Extra | Describes additional operations such as filtering, sorting and temporary tables |
Consider this illustrative execution plan:
id select_type table type possible_keys key key_len rows Extra
1 SIMPLE orders range idx_orders_user_page idx_orders_user_page 13 120 Using whereThe selected index is idx_orders_user_page. MySQL estimates that it will examine 120 rows.
The exact values depend on the schema, data distribution, parameter values and optimizer decisions. Treat this as an example, not a guaranteed result.
The most useful columns to inspect first are type, key, rows and Extra.
Table access types
The type column describes how MySQL retrieves rows from a table. It helps you distinguish an indexed lookup from a scan across a large portion of the table.
The access type is one of the first places to investigate when a query becomes slow.
Access type ordering
The following types commonly appear in MySQL execution plans:
| Type | Meaning |
|---|---|
const | At most one matching row from a constant lookup, usually through a primary key or unique index |
eq_ref | At most one matching row for each combination of previously accessed rows, using a primary key or unique index |
ref | Matching rows retrieved through a non-unique index |
range | Rows retrieved from an index range |
index | A full index scan |
ALL | A full table scan |
This is an approximate guide to access efficiency. The best access type depends on the query and the amount of data examined.
Consider three examples.
A full table scan:
table type key rows
orders ALL NULL 500000MySQL expects to examine the entire orders table. The key value is NULL, so no index is selected for row lookup.
An index range scan:
table type key rows
orders range idx_orders_user_page 120MySQL uses an index to navigate a range of matching values.
An indexed equality lookup:
table type key rows
orders ref idx_orders_user_page 45MySQL uses an index to retrieve rows matching an equality condition. Because this is a non-unique index, multiple rows can match.
Full table scans
Access types help you identify when MySQL examines substantially more data than the query requires.
Suppose the endpoint needs the most recent 20 orders for one customer, but MySQL examines 500,000 rows.
That is a potential performance problem as the table grows.
However, ALL does not automatically mean the query is inefficient. A small table can be faster to scan than to access through an index. MySQL may also choose a scan when a condition matches a large proportion of the rows.
Similarly, index is not necessarily bad. A scan of a relatively small covering index can be cheaper than reading the full table.
The objective is not to eliminate every scan. You want an access method appropriate for the amount of data the query needs.
Selected indexes and row estimates
The key column tells you which index MySQL actually selects.
The possible_keys column tells you which indexes it considered. An index appearing in possible_keys does not mean MySQL will use it.
For example:
possible_keys: idx_orders_user_page
key: NULLMySQL considered the index but did not select it for row lookup.
Investigate the query conditions, index structure, data distribution and optimizer estimates before adding another index.
Key length
The key_len column reports the number of bytes of the selected index key used by the lookup.
It is not a count of indexed columns.
For a composite index, this value can help you understand how much of the index participates in the lookup. Its value depends on column types, nullability and character sets.
If the query uses only the leading user_id condition, the remaining columns may not participate in range navigation even though MySQL selects the composite index.
Estimated rows
The rows column estimates how many rows MySQL expects to examine.
Suppose your endpoint returns 20 orders, but the execution plan estimates that it must examine 40,000 rows.
That difference deserves investigation.
Possible explanations include:
- An unsuitable index.
- An unselective condition.
- Inaccurate optimizer statistics.
- A query condition that prevents efficient index navigation.
The filtered column provides additional context. It estimates the percentage of examined rows that pass the remaining conditions.
A large rows estimate combined with a small filtered percentage can indicate that MySQL performs substantial work before producing the requested result.
B-tree indexes
MySQL's InnoDB storage engine uses B-tree structures for its ordinary indexes.
A B-tree index keeps indexed values organized so that MySQL can navigate to a matching key or a range of keys without scanning every row.
For example, an index on user_id allows MySQL to locate a customer's orders without examining unrelated customers' rows.
The structure also supports ordered traversal. This becomes important when an endpoint returns recent orders in a particular order.
Composite indexes
A composite index contains multiple columns in a defined order.
The order history index is:
CREATE INDEX idx_orders_user_page
ON orders (user_id, created_at, id);The column order reflects the query's requirements:
user_ididentifies the customer.created_atparticipates in pagination and ordering.idprovides a tie-breaker when multiple orders have the same timestamp.
The index is not equivalent to three separate single-column indexes. MySQL can navigate its ordered key structure using the leading indexed columns.
The leftmost-prefix rule
The leftmost-prefix rule describes how MySQL uses the leading columns of a composite index.
For this index:
CREATE INDEX idx_orders_user_page
ON orders (user_id, created_at, id);MySQL can use the index's leading column for a lookup on user_id.
It can also use the leading pair for conditions involving user_id and created_at.
However, a query filtering only on created_at does not have the same leading-column lookup because user_id comes first.
Consider these conditions:
| Query condition | Leading index usage |
|---|---|
user_id = ? | Yes |
user_id = ? AND created_at < ? | Yes |
user_id = ? AND created_at = ? AND id = ? | Yes |
created_at < ? | No equivalent leading-column lookup |
This explains why index column order matters.
An index on (created_at, user_id, id) is not interchangeable with (user_id, created_at, id). The former does not provide the same efficient lookup for a particular customer's order history.
Keyset pagination and index order
The order history query uses:
WHERE user_id = ?
AND (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT 21;The equality condition comes first. The timestamp and ID then identify the portion of the customer's orders that belongs to the requested page.
The composite index matches this access pattern:
CREATE INDEX idx_orders_user_page
ON orders (user_id, created_at, id);MySQL 8 can scan an ascending index backwards to satisfy descending ordering.
You do not need to create a separate descending index merely because the query uses DESC.
The important requirement is that the index supports the query's leading equality condition and the remaining range and ordering columns.
Secondary indexes and covering indexes
In InnoDB, the primary key determines the clustered organization of table records. A secondary index stores its indexed columns along with the primary-key value needed to locate the corresponding clustered record.
This matters when designing indexes because a query might need data that the secondary index does not contain.
Consider a query that selects only columns already available in an index:
SELECT user_id, created_at, id
FROM orders
WHERE user_id = ?;MySQL may satisfy this query directly from the index.
The Extra column can report:
Using indexThis means that the selected index covers the data needed by the query. MySQL does not need to retrieve the corresponding full table records for those selected columns.
By contrast, selecting columns such as total_paise or status may require additional access to the clustered records unless the selected index also covers them.
Avoid SELECT * in performance-sensitive endpoints when the handler needs only a small number of columns.
A covering index can reduce table lookups, but adding every selected column to every index is not a good strategy. Secondary indexes consume storage and increase the work required for inserts, updates and deletes.
The Extra column
The Extra column describes operations that do not fit into the other execution-plan columns.
Several values are particularly useful when investigating slow queries.
Using where
Using where means MySQL applies a condition to filter rows.
This is common and does not automatically indicate a problem.
Check how many rows MySQL examines before applying the condition. A query that examines 100 rows and returns 20 may be perfectly reasonable. One that examines 500,000 rows and returns 20 deserves investigation.
Using filesort
Using filesort means MySQL performs an additional sorting operation because the selected access path does not directly provide the required ordering.
Suppose your order history query requests:
ORDER BY created_at DESC, id DESCIf MySQL cannot use an index to provide that order, it may report:
Extra: Using where; Using filesortA sort operation can increase work when many candidate rows need sorting before the LIMIT can be applied.
The name is misleading. Filesort does not necessarily mean MySQL writes the sorted data to disk. The sorting mechanism can use memory or temporary disk storage depending on the operation and available resources.
For a paginated order history query, Using filesort is a reason to inspect whether the composite index matches the equality conditions and ORDER BY columns.
It is not proof by itself that a particular index must be added. First check the selected key, access type and query shape.
Using temporary
Using temporary indicates that MySQL creates an internal temporary table while processing the query.
This can occur during grouping, sorting and other operations.
Large temporary tables can increase memory usage and cause disk activity. Investigate the query structure and number of intermediate rows rather than treating every temporary table as a failure.
Backward index scan
MySQL 8 can scan an ascending index backwards to satisfy descending ordering.
For the order history index, a descending query can use the same index:
ORDER BY created_at DESC, id DESCA backward index scan is not inherently expensive. It may be exactly the access pattern the query requires.
Query conditions and index usability
An index can exist without being useful to a particular query.
Consider this example:
SELECT id, status, created_at
FROM orders
WHERE DATE(created_at) = '2026-11-04';Applying DATE() to the indexed column can prevent MySQL from efficiently navigating the index using the original timestamp values.
A range condition expresses the same date requirement without applying a function to the column:
SELECT id, status, created_at
FROM orders
WHERE created_at >= '2026-11-04 00:00:00'
AND created_at < '2026-11-05 00:00:00';This form allows MySQL to use an appropriate timestamp index for range navigation.
The general principle is to inspect how query conditions interact with the index structure. Do not assume that the existence of an index guarantees its use.
The restaurants geographic index
The restaurants table contains geographic coordinates and an active-state field.
Its geographic index is:
CREATE INDEX idx_rest_geo
ON restaurants (lat, lng);The index supports lookups that constrain the leading lat column and use lng as part of the access condition.
A query filtering only on lng cannot use the same leading-column lookup effectively.
The index order matters because of the leftmost-prefix rule.
The is_active column can also appear in restaurant-list conditions. However, adding an index on a low-cardinality column may provide little benefit when many restaurants share the same value.
Think about the actual number of matching rows before creating another index.
Each additional index uses storage and increases write work. You should create an index to support an observed query pattern, not because a column appears in a WHERE clause.
EXPLAIN ANALYZE
Plain EXPLAIN reports optimizer estimates. It does not execute the query and report its actual execution timings.
MySQL 8 also supports EXPLAIN ANALYZE.
Consider an order history query using a representative customer ID:
EXPLAIN ANALYZE
SELECT id, user_id, restaurant_id, status, total_paise, created_at
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 21;EXPLAIN ANALYZE executes the statement and reports actual timing and row-count information for operations in the execution plan.
This lets you compare the optimizer's estimated work with what happened during execution.
For example:
Estimated rows: 5000
Actual rows: 80A substantial difference deserves investigation. The optimizer's statistics or assumptions may not reflect the actual data distribution.
Look at both estimated and actual rows. Also inspect how much time each operation consumes.
Use realistic seed data when evaluating query plans. Remember that EXPLAIN ANALYZE executes the statement, so avoid running expensive queries indiscriminately against production data.
SHOW PROCESSLIST
An efficient execution plan does not guarantee that MySQL is healthy during concurrent traffic.
A load test may reveal long-running statements, connections waiting for resources or queries occupying connections for too long.
MySQL provides SHOW PROCESSLIST to inspect active database connections and their current statements.
Run:
SHOW PROCESSLIST;For complete SQL statement text, use:
SHOW FULL PROCESSLIST;The output contains several useful columns:
| Column | Meaning |
|---|---|
Id | Connection identifier |
User | MySQL account associated with the connection |
Host | Client host and port |
db | Current database |
Command | Current command, such as Query or Sleep |
Time | Seconds spent in the current state |
State | What the connection is currently doing |
Info | Current SQL statement, when available |
Consider this illustrative output:
Id User db Command Time State Info
101 app_user zomato Sleep 1 NULL
102 app_user zomato Query 18 executing SELECT ...
103 app_user zomato Sleep 2 NULLA few sleeping connections are normally healthy. Go reuses idle connections instead of establishing a new MySQL connection for every request.
However, several connections executing the same statement for a long time deserve investigation.
Look at the SQL statement, its execution plan and the number of rows examined. Determine whether the query itself is slow or waiting on another resource.
Connection-pool saturation
The Go backend uses database/sql to manage MySQL connections.
The connection pool controls how many database connections the application can open and keep available.
For example:
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)SetMaxOpenConns limits the number of open connections. SetMaxIdleConns controls how many connections can remain idle for reuse.
Without a suitable maximum, the application can open more connections than the database can support.
In the next exercise you read the open limit from DB_MAX_OPEN_CONNS and choose a bounded default; the test accepts any default from 1 to 100. The idle connection limit must never exceed the open limit.
Increasing the pool size does not automatically improve performance. More concurrent queries can increase database contention and make query latency worse.
Pool statistics
Go exposes connection-pool information through db.Stats().
stats := db.Stats()
fmt.Println("Open:", stats.OpenConnections)
fmt.Println("In use:", stats.InUse)
fmt.Println("Idle:", stats.Idle)
fmt.Println("Wait count:", stats.WaitCount)
fmt.Println("Wait duration:", stats.WaitDuration)The important fields are:
OpenConnections: Current number of open connections.InUse: Connections currently being used.Idle: Connections available for reuse.WaitCount: Total number of times a request waited for a connection.WaitDuration: Total time spent waiting for connections.
If InUse remains at the configured maximum and WaitCount increases, requests are waiting for available connections.
This does not automatically mean the pool needs a larger limit. Long-running queries might be occupying connections for too long.
Increasing the limit without addressing those queries can increase database load and make contention worse.
The bottleneck investigation adds Prometheus gauges and counters that expose the pool statistics through /metrics. These measurements let you observe pool usage while k6 sends traffic.
Query investigation workflow
Use a repeatable investigation process instead of adding indexes whenever an endpoint becomes slow.
- Identify the slow endpoint, such as restaurant discovery or order history.
- Capture the actual SQL statement and representative parameters.
- Run
EXPLAINand inspecttype,possible_keys,key,key_len,rowsandExtra. - Check whether the selected index matches the equality conditions and ordering requirements.
- Run
EXPLAIN ANALYZEto compare estimated and actual rows and timings. - Inspect
SHOW FULL PROCESSLISTduring representative traffic. - Compare database-pool usage, wait counts and wait duration.
- Change one thing at a time and run the same workload again.
A query plan is evidence about how MySQL accesses data. It is not a performance guarantee.
A query can be efficient in isolation but become a bottleneck when hundreds of requests execute it simultaneously. Validate your findings against actual latency and resource measurements.
EXPLAIN and bottleneck investigation
The exercise "Find and fix the first bottleneck" uses these techniques alongside CPU profiling and k6 measurements.
You inspect the order history index (user_id, created_at, id) and determine whether MySQL uses it effectively. You also inspect SHOW PROCESSLIST and the database-pool measurements to distinguish slow queries from connection waits.
Do not assume that MySQL is responsible for every latency problem. The in-memory rate limiter mutex, menu assembly allocations and network activity can also affect the measured request duration.
The exercise requires one targeted change per run and a comparison of before and after p50, p95, p99 and error rate.
Use the query plan to explain what MySQL is doing. Use the load-test measurements to establish whether the change actually improved the backend.
Check your understanding
You run EXPLAIN on the order history query and see type = ALL, key = NULL and rows = 300000. What does this indicate?
References
Everything above is explained on this page; these are where it comes from (MySQL 8.4).