Execution Plans and Slow Query Investigation

Inspect access methods with execution plans and improve time filters and continuous pagination

🎯 Introduction

By the end of this article, you will be able to inspect access methods with execution plans and improve time filters and continuous pagination.


🧰 Inspect the planned access method with EXPLAIN

This article uses the following original query_user dataset:

idusernameagecitycreated_at
1Xiao Ming25Beijing2026-10-01 09:00:00
2Xiao Hong30Shanghai2026-10-02 09:00:00
3Xiao Gang22Beijing2026-10-03 09:00:00
4Xiao Lin30Shanghai2026-10-04 09:00:00
5Xiao AnNULLHangzhou2026-10-05 09:00:00

Initialize it using Query practice data if needed. First create the idx_query_city_age composite index on city and age from Index design, then inspect this query:

EXPLAIN SELECT id, city, age FROM query_user
WHERE city = 'Beijing' AND age >= 23;

EXPLAIN returns the query plan, not Xiao Ming's data. Start with these fields:

FieldMeaningHow to interpret it
possible_keysPotentially applicable indexesNot the final choice
keyIndex selected for the planNULL means no lookup index was selected
typeAccess methodALL is a full table scan; range is range access
rowsEstimated rows examinedAn estimate, not the actual returned row count
ExtraAdditional processingUsing index often means all required columns are available in the index

If key shows idx_query_city_age, the plan uses that composite index. Table size, data distribution, and statistics affect the choice. Do not assume one fixed output applies to every environment.


⏱ EXPLAIN ANALYZE actually executes the query

EXPLAIN ANALYZE SELECT id, city, age FROM query_user
WHERE city = 'Beijing' AND age >= 23;

The output is a tree of steps. actual time reports measured time, rows is the average number of rows produced per loop at that step, and loops is the number of executions. Assess the work across steps rather than checking only whether an index appears.

It actually runs the SELECT. Test broad queries in a test environment or a controlled time window first; this is not a cost-free inspection command.


🗓 Use time ranges instead of converting every row

To query users from one day, constrain the time column directly:

SELECT id, username FROM query_user
WHERE created_at >= '2026-10-03' AND created_at < '2026-10-04';

Query result:

idusername
3Xiao Gang

This returns Xiao Gang. Compared with applying DATE to every created_at value before comparing it, a range condition makes it easier to use an ordinary index on the time column.

If this query is frequent and the dataset is large, create:

CREATE INDEX idx_query_created_at ON query_user (created_at);

Run EXPLAIN again after creating it and compare. Improving the SQL does not guarantee that a small table will use the index or that elapsed time will noticeably decrease.


📄 Avoid skipping more and more rows when loading subsequent batches

With a large OFFSET, the database typically still processes the skipped records. If the page only needs to load the next batch, retain the last id from the previous batch.

First, retrieve the two lowest IDs:

SELECT id, username FROM query_user ORDER BY id LIMIT 2;

Query result:

idusername
1Xiao Ming
2Xiao Hong

The result contains IDs 1 and 2; the client remembers 2. Start the next batch directly after 2:

SELECT id, username FROM query_user WHERE id > 2 ORDER BY id LIMIT 2;

Query result:

idusername
3Xiao Gang
4Xiao Lin

This returns IDs 3 and 4. The primary key provides both a deterministic order and a starting point. This approach is called cursor pagination.

It suits sequential loading and does not directly replace jumping to page 100. When sorting by time, the cursor must store both the time and an id to break ties, and the query conditions must match the ordering.


🐢 Start with actual slow statements

First determine whether time is spent waiting for a connection, executing in the database, or returning data. Application logs can record the operation name, duration, and returned row count. Avoid logging raw parameters such as passwords.

The database also has a slow query log for SQL meeting conditions such as exceeding a duration threshold. Check whether it is enabled:

SHOW VARIABLES LIKE 'slow_query_log';

For example, when slow query logging is disabled:

Variable_nameValue
slow_query_logOFF

ON means enabled; OFF means disabled. Inspect the current connection's duration threshold:

SHOW VARIABLES LIKE 'long_query_time';

For example, with a threshold of 10 seconds:

Variable_nameValue
long_query_time10.000000

The unit is seconds. Connection settings can differ, and operational configuration determines the actual collection rules. Before enabling logging or lowering thresholds in production, consider log volume and sensitive data. Do not change global configuration inside ordinary API requests.

Once you have a specific slow SQL statement, inspect its filter range, rows scanned, unnecessary returned columns, and repeated execution before considering indexes. Seeing ALL does not justify indexing every column.


❓ Questions and Answers

Q1: Does Using filesort always mean disk was used?

No. It indicates additional sorting. Whether that spills to disk depends on factors such as data volume and available memory.

Q2: What if the rows estimate is inaccurate?

At an appropriate time, update statistics with ANALYZE TABLE and compare plans again. This also has an execution cost; do not run it before every query.

Q3: Can adding an index fix lock waits?

A suitable index may reduce scanning and the locking range, but long transactions and competing updates still need investigation. Indexes alone cannot resolve every wait.


🧪 Exercise

Run EXPLAIN for a time-range query and record key, type, and rows. Then run EXPLAIN ANALYZE and distinguish estimates from actual execution results.

-- Write your SQL or record your verification results here