Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to read MySQL EXPLAIN and EXPLAIN ANALYZE execution plans. Decode join types, scan costs, filtered percentages, and execution tree timings.
Quick answer
MySQL EXPLAIN displays how the query optimizer plans to execute a query, including index selection and join order. MySQL 8.0 EXPLAIN ANALYZE actually executes the query, outputting a tree plan comparing estimated costs and rows against real-world execution times and actual row counts.
FAQs
Does EXPLAIN ANALYZE execute the query in MySQL?
Yes! Unlike standard EXPLAIN which only plans, EXPLAIN ANALYZE actually executes the query to measure timing. Do not run EXPLAIN ANALYZE on destructive UPDATE or DELETE queries in production!
What does "type: ref" mean in MySQL EXPLAIN?
type: ref means MySQL uses a non-unique index to look up matching rows. It is an efficient index access type, second only to primary key lookups (const and eq_ref).
Why does my query show "Using filesort" even though I have an index?
If the index order does not match the ORDER BY direction (ASC vs DESC) or includes columns not present in the index prefix, MySQL must sort results in memory using filesort.
How do I view JSON-formatted execution plans in MySQL?
Run EXPLAIN FORMAT=JSON followed by your query. This outputs detailed cost metrics, query block IDs, and buffer usage numbers.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
Learn how to cache complex analytical queries with PostgreSQL materialized views. Master REFRESH MATERIALIZED VIEW CONCURRENTLY, indexing, and scheduling.
When a MySQL query runs slowly in production, guessing which index to add is a recipe for wasted engineering time. The definitive tool for diagnosing slow queries in MySQL is EXPLAIN. In MySQL 8.0, the introduction of EXPLAIN ANALYZE provides deep visibility by executing the query and measuring real execution time.
Traditional tabular EXPLAIN shows what the optimizer predicts will happen. EXPLAIN ANALYZE shows what actually happened. Learning how to interpret both formats allows you to pinpoint missing indexes, inaccurate row estimates, and inefficient join strategies instantly.
Traditional tabular EXPLAIN: key columns decoded
Prefixing any SELECT, UPDATE, or DELETE statement with EXPLAIN outputs a tabular summary of the execution plan. Read our SQL query performance checklist for diagnostic steps.
Running standard MySQL EXPLAIN
EXPLAIN SELECT o.order_id, c.customer_name, o.total_amountFROM customers cJOIN orders o ON o.customer_id = c.customer_idWHERE c.country = 'US' AND o.status = 'shipped';
The most critical columns in the tabular output are:
type: The join access type. Ranked best to worst: const, eq_ref, ref, range, index, ALL. Seeing ALL means a full table scan.
possible_keys: The indexes MySQL considered using.
key: The actual index the optimizer chose to execute the lookup.
rows: The estimated number of rows MySQL expects to inspect.
filtered: The estimated percentage of rows that will satisfy remaining table filters (100% is optimal).
Extra: Important operational flags like Using index (covering index), Using temporary (memory table created), or Using filesort (in-memory/disk sorting).
MySQL 8.0 EXPLAIN ANALYZE: real tree execution metrics
Starting in MySQL 8.0.18, EXPLAIN ANALYZE outputs a formatted execution tree detailing exact timings and row counts for each iterator in the plan.
Running MySQL EXPLAIN ANALYZE
EXPLAIN ANALYZESELECT o.order_id, c.customer_name, o.total_amountFROM customers cJOIN orders o ON o.customer_id = c.customer_idWHERE c.country = 'US' AND o.status = 'shipped';-- Example Output:-- -> Nested loop inner join (cost=1120.45 rows=450) (actual time=0.125..4.812 rows=412 loops=1)-- -> Filter: (c.country = 'US') (cost=120.25 rows=150) (actual time=0.082..1.120 rows=145 loops=1)-- -> Table scan on c (cost=120.25 rows=1000) (actual time=0.078..0.985 rows=1000 loops=1)-- -> Index lookup on o using idx_orders_customer (customer_id=c.customer_id), with index condition: (o.status = 'shipped') (cost=2.15 rows=3) (actual time=0.021..0.024 rows=3 loops=145)
According to the MySQL EXPLAIN statement documentation, the output tree reads from inside out: innermost indented operations execute first. For each node, (actual time=A..B rows=C loops=D) reports:
A: Time in milliseconds to retrieve the first row.
B: Time in milliseconds to retrieve all rows from this iterator.
C: Total rows returned across all executions.
D: Number of times this node was executed (loops).
Spotting cardinality misestimates
The greatest value of EXPLAIN ANALYZE is comparing estimated rows against actual rows. In the example above, the optimizer estimated rows=3 per customer, and the actual execution returned rows=3 across 145 loops, showing accurate statistics.
If the optimizer estimates rows=10 but actual execution processes rows=1,500,000, the table statistics are stale. The optimizer chose a Nested Loops plan thinking the dataset was tiny, whereas a Hash Join was appropriate. Running ANALYZE TABLE customers; refreshes distribution histograms and corrects plan selection.
Decoding warning flags in the Extra column
Certain flags in the Extra column signal urgent optimization needs:
Using filesort: MySQL must perform an extra pass to sort rows. Add an index matching the ORDER BY clause to read rows pre-sorted.
Using temporary: MySQL creates an internal temporary table to process grouping or distinct filters. Revisit query structure or increase memory limits.
Using join buffer (Block Nested Loop): MySQL joins tables without indexes, buffering rows in memory. Add an index on the join foreign key column.
Actionable checklist for reading MySQL query plans
Run EXPLAIN on slow queries: inspect type column; eliminate ALL (full table scans) with appropriate indexes.
Use EXPLAIN ANALYZE in staging: verify actual execution time vs estimated rows in MySQL 8.0+.
Compare estimated vs actual rows: run ANALYZE TABLE if actual row counts diverge significantly from estimates.
Eliminate Using filesort on high-frequency queries: align composite index columns with ORDER BY clauses.
Look for covering indexes: aim for Extra: Using index to satisfy queries directly from B-tree memory buffers.
Check join loops: multiply actual time by loops count to identify the true bottleneck in nested loop plans.
Wrapping up
Mastering MySQL EXPLAIN and EXPLAIN ANALYZE transforms database performance tuning from guesswork into an empirical science. By decoding join types, verifying cardinality estimates, and eliminating filesorts, you guarantee predictable query latency. Format your complex MySQL queries and index definitions with sqlfmt or explore our pricing options.