How to Use EXPLAIN ANALYZE in MySQL 8: Reading the Execution Tree, Analyzing Costs, and Measuring Actual Query Execution Time

MySQL tutorial - IT technology blog
MySQL tutorial - IT technology blog

The Problem: Why Does a Query Run Slowly When Everything Looks Fine?

Your maps app says the drive from home to the office will only take 15 minutes because traffic is clear. Two blocks out of your neighborhood, however, a gridlocked intersection turns the trip into a 50-minute crawl. Looking only at the initial forecast won’t tell you where you’re actually stuck.

Database queries work the exact same way. Traditionally, when a SQL query dragged its feet, engineers turned to the classic EXPLAIN command. It only draws MySQL’s “predicted route” before running the query—estimating how many rows need to be read or whether an index will be used.

When our users table crossed 10 million rows, I started running into slow queries and had to tune our indexes. EXPLAIN reported that everything looked great, yet the webpage still spun for 4–5 seconds before loading. The culprit was skewed data distribution, which threw MySQL’s estimates completely off. Since MySQL 8.0.18, we have EXPLAIN ANALYZE. It actually runs the query, times each step, and points directly to the bottleneck.

Core Concepts: What Are EXPLAIN ANALYZE and the Execution Tree?

You don’t need to memorize complex query optimization theory. Just grasp the three points below and you’ll be able to read the output right away.

How Does EXPLAIN Differ from EXPLAIN ANALYZE?

The biggest difference comes down to actual execution. The traditional EXPLAIN only asks the Optimizer what MySQL plans to do, so it returns instantly without touching your data. By contrast, EXPLAIN ANALYZE executes the query, clocks every stage, and returns a detailed report.

Because it actually runs the query, keep one vital rule in mind: if the original query takes 10 seconds and spikes CPU usage, EXPLAIN ANALYZE will also take 10 seconds and consume the exact same resources.

The Execution Tree and the Inside-Out Reading Rule

Instead of returning a flat table like before, EXPLAIN ANALYZE prints a hierarchical structure called an Execution Tree. Visually, it looks like an indented bulleted list using -> arrows.

Think of it like a kitchen assembly line. Someone preps the vegetables before passing them to the person who washes them, and only then does the chef stir-fry them. In an Execution Tree, the most deeply indented lines on the inside run first, passing their results up to their parent nodes on the outside.

Four Key Metrics to Watch

Each node in the execution tree has two sets of parentheses: one shows the initial estimates, and the other shows the actual measured results.

  • cost (Estimated cost): A relative number calculated by MySQL before execution. A higher cost means MySQL expects that step to be heavier.
  • actual time=X..Y (Actual time in milliseconds): X is the average time to retrieve the first row; Y is the average time to finish reading all rows in a single loop.
  • rows (Actual rows): The average number of rows returned by this step per loop.
  • loops (Loop count): How many times this step had to repeat. The true total time for a step is roughly Y * loops. If you see a tiny actual time paired with hundreds of thousands of loops, you’ve found your culprit.

Hands-On Walkthrough: Inspecting Every Millisecond with EXPLAIN ANALYZE

Enough theory. Let’s inspect a real query on a dataset with 1 million rows in the users table and roughly 4 million rows in the orders table.

Step 1: Run the Query Before Index Optimization

Our goal is to find completed orders for active users located in Hanoi. Here is the SQL query:

EXPLAIN ANALYZE
SELECT u.id, u.email, o.total_amount
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.city = 'Hanoi'
  AND u.status = 'active'
  AND o.status = 'completed';

MySQL 8 executes the query and returns the following Execution Tree:

-> Nested loop inner join  (cost=185420.15 rows=45000) (actual time=12.450..1842.310 rows=38420 loops=1)
    -> Filter: ((u.city = 'Hanoi') and (u.status = 'active'))  (cost=98500.00 rows=12000) (actual time=8.120..940.500 rows=15200 loops=1)
        -> Table scan on u  (cost=98500.00 rows=1000000) (actual time=0.450..680.220 rows=1000000 loops=1)
    -> Filter: (o.status = 'completed')  (cost=0.65 rows=3) (actual time=0.045..0.058 rows=2.5 loops=15200)
        -> Index lookup on o using idx_user_id (user_id=u.id)  (cost=0.65 rows=5) (actual time=0.038..0.049 rows=4.2 loops=15200)

Step 2: Analyze the Execution Tree to Find the Bottleneck

Reading from the inside out and top to bottom along each branch, three issues stand out:

  1. First branch (users table): The deepest line is Table scan on u. MySQL reads all 1 million rows (rows=1000000), taking 680.220 ms. Moving up one level, Filter narrows down by city and status, keeping 15,200 rows and bringing this branch’s total to 940.500 ms. Nearly 1 second is spent just filtering users.
  2. Second branch (orders table): Thanks to the existing idx_user_id, the Index lookup itself is blazing fast at just 0.049 ms per call. However, look at loops=15200. For every user found in the first branch, MySQL has to probe the orders table once, spending a combined 0.058 * 15200 ≈ 881 ms.
  3. Join step (Nested loop inner join): Combining both stages, the entire query takes 1842.310 ms (nearly 1.85 seconds).

Step 3: Create a Composite Index and Re-Check the Results

The first culprit is clearly the Table scan on the users table. Let’s add a composite index covering the two columns frequently filtered together—city and status:

CREATE INDEX idx_users_city_status ON users (city, status);

Running the exact same EXPLAIN ANALYZE query again yields a dramatic improvement:

-> Nested loop inner join  (cost=14250.40 rows=38420) (actual time=0.850..895.120 rows=38420 loops=1)
    -> Index lookup on u using idx_users_city_status (city='Hanoi', status='active')  (cost=3200.10 rows=15200) (actual time=0.310..24.600 rows=15200 loops=1)
    -> Filter: (o.status = 'completed')  (cost=0.65 rows=3) (actual time=0.044..0.056 rows=2.5 loops=15200)
        -> Index lookup on o using idx_user_id (user_id=u.id)  (cost=0.65 rows=5) (actual time=0.037..0.048 rows=4.2 loops=15200)

In the users branch, both Table scan and Filter are gone, replaced by Index lookup on u using idx_users_city_status. Processing time for the users table dropped from 940.5 ms down to 24.6 ms—a 38x speedup. Total query time was cut by more than half, down to 895 ms. Most of the remaining time (about 850 ms) comes from the 15,200 loops into the orders table. To optimize further, you could add a (user_id, status) index on orders or restrict the result set with LIMIT.

Safety Tips for Running in Production

  • Be careful with write statements: EXPLAIN ANALYZE works with SELECT, UPDATE, and DELETE. If you put it in front of a DELETE statement, your data will actually be deleted. Wrap write queries in BEGIN; ... ROLLBACK; or rewrite them as an equivalent SELECT to test safely.
  • Avoid running on an overloaded production database: If the original query takes 30 seconds, EXPLAIN ANALYZE will burn resources for those exact 30 seconds as well. Prefer testing on a replica or a staging environment with comparable data volume.

Conclusion

Stop guessing when tuning SQL queries. EXPLAIN ANALYZE in MySQL 8 gives you real measurements down to the millisecond through the Execution Tree. Just read from the deepest branch outward, pay close attention to actual time and loops, and you’ll pinpoint the exact bottleneck to fix.

Share: