Home / Databases / MySQL

DatabasesCheat sheetAdvanced

MySQL optimizer cheat sheet: EXPLAIN ANALYZE, optimizer trace, index statistics, histograms and hints

Commands for working out why MySQL chose a plan. Read EXPLAIN ANALYZE, trace the cost decisions, fix row estimates with index statistics and histograms, and pin plans with hints when you have to.

Deepak Bhardwaj6 min read

Applies toMySQL 8.0 (8.0.18 and later for EXPLAIN ANALYZE) and 8.4 LTS; Amazon RDS and Aurora MySQL 3, Azure Database for MySQL Flexible Server

When to use this

A query picked a full scan, the wrong index or a bad join order, and you need to know why before you add an index or a hint. The workflow is: see the plan with actual row counts, find where the estimate and the actual count diverge, read the trace for that decision, then fix the statistics. Use a hint only as a last resort.

Plans: estimated and actual

-- Estimated plan, tree format (8.0.16+)
EXPLAIN FORMAT=TREE
SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'OPEN' AND o.created_at >= NOW() - INTERVAL 1 DAY;

-- Runs the query and reports actual time, rows and loops per iterator (8.0.18+)
EXPLAIN ANALYZE
SELECT ...;

-- JSON plan with cost details
EXPLAIN FORMAT=JSON SELECT ...;

-- Plan for a statement running in another connection
EXPLAIN FOR CONNECTION 12345;

Warning

EXPLAIN ANALYZE executes the statement. For SELECT that only costs time and load. Don't use it on a slow query at peak on the primary. Run it on a replica or a restored copy.

How to read EXPLAIN ANALYZE lines:

Field Meaning
cost=... rows=N Optimizer estimate
actual time=a..b ms to first row .. ms to all rows, per loop
rows=M (in the actual block) Actual rows per loop
loops=L How many times the iterator ran. Total rows = M × L

Look for the first iterator, reading from the inside out, where estimated rows and actual rows differ by 10× or more. Everything above it was planned on bad numbers.

Traditional EXPLAIN columns worth checking

Column / value Red flag
type = ALL Full table scan
type = index Full index scan (often no better than ALL)
key = NULL with possible_keys set Optimizer rejected the indexes on cost
rows × filtered Small filtered on a large rows means a weak access path
Extra: Using filesort / Using temporary Sort or group not satisfied by an index
Extra: Using join buffer (hash join) No usable index on the join column

Optimizer trace: why it chose this plan

SET SESSION optimizer_trace = 'enabled=on';
SET SESSION optimizer_trace_max_mem_size = 4194304;   -- default is too small for big queries
SELECT ...;                                           -- or EXPLAIN SELECT ...
SELECT TRACE FROM information_schema.OPTIMIZER_TRACE\G
SET SESSION optimizer_trace = 'enabled=off';

What to look for in the JSON:

  • rows_estimation → range_analysis → analyzing_range_alternatives: the cost and rows for each candidate index, and why each was rejected ("cause": "cost").
  • considered_execution_plans: the join orders tried, with their costs.
  • MISSING_BYTES_BEYOND_MAX_MEM_SIZE greater than 0 means the trace was truncated. Raise the memory size.

Index statistics (InnoDB)

-- Persistent statistics for a table
SELECT index_name, stat_name, stat_value, sample_size, last_update
FROM mysql.innodb_index_stats
WHERE database_name = 'app' AND table_name = 'orders';

SELECT n_rows, clustered_index_size, last_update
FROM mysql.innodb_table_stats
WHERE database_name = 'app' AND table_name = 'orders';

-- Cardinality as the optimizer sees it
SHOW INDEX FROM app.orders;

-- Recalculate (cheap; takes a brief metadata lock at the end)
ANALYZE TABLE app.orders;

-- Sample more pages for a skewed big table (default innodb_stats_persistent_sample_pages = 20)
ALTER TABLE app.orders STATS_SAMPLE_PAGES = 200;
ANALYZE TABLE app.orders;
Variable Default Note
innodb_stats_persistent ON Statistics survive restarts
innodb_stats_auto_recalc ON Recalculates after about 10% of rows change
innodb_stats_persistent_sample_pages 20 Raise per table rather than globally

Histograms for non-indexed columns

Index statistics only cover indexed columns. When the filter is on a skewed, non-indexed column (status, country, type), the optimizer guesses its selectivity. A histogram fixes that guess without the write cost of an index.

ANALYZE TABLE app.orders UPDATE HISTOGRAM ON status, region WITH 64 BUCKETS;

SELECT schema_name, table_name, column_name,
       histogram->>'$."histogram-type"' AS type,
       histogram->>'$."number-of-buckets-specified"' AS buckets,
       histogram->>'$."last-updated"' AS updated
FROM information_schema.COLUMN_STATISTICS
WHERE schema_name = 'app';

ANALYZE TABLE app.orders DROP HISTOGRAM ON region;

Tip

Histograms don't refresh themselves by default. Schedule UPDATE HISTOGRAM after big data changes. If the column is indexed, the optimizer uses index dives for ranges instead and the histogram is often ignored, so histograms pay off most on columns without an index.

Index dives and long IN lists

SHOW VARIABLES LIKE 'eq_range_index_dive_limit';   -- default 200

Above this many equality ranges (for example, IN (...) with 500 values), MySQL switches from index dives to index statistics for its estimate. That can flip the plan. Batch long lists, or check that the statistics are accurate.

Switches and hints

SELECT @@optimizer_switch\G

-- Per statement, without changing the session
SELECT /*+ SET_VAR(optimizer_switch = 'index_merge=off') */ ...;

-- Choose or block indexes (INDEX/NO_INDEX hints: 8.0.20+)
SELECT /*+ INDEX(o idx_orders_status_created) */ ... FROM orders o ...;
SELECT /*+ NO_INDEX(o idx_orders_created) */ ...;

-- Join order
SELECT /*+ JOIN_ORDER(c, o) */ ... FROM orders o JOIN customers c ...;
SELECT /*+ JOIN_PREFIX(c) */ ...;

-- Guardrail on runtime for SELECT, in ms
SELECT /*+ MAX_EXECUTION_TIME(5000) */ ...;

-- Older index hint syntax
SELECT ... FROM orders o FORCE INDEX (idx_orders_status_created) ...;

Hints break silently when an index is renamed or dropped. The query still runs, with whatever plan the optimizer then picks. Track every hinted statement in source control.

Test an index drop without dropping it

ALTER TABLE app.orders ALTER INDEX idx_orders_legacy INVISIBLE;
-- watch performance; to check what the plan would be with it:
SET SESSION optimizer_switch = 'use_invisible_indexes=on';
EXPLAIN SELECT ...;
ALTER TABLE app.orders ALTER INDEX idx_orders_legacy VISIBLE;   -- instant rollback

Invisible indexes are still maintained on writes, and the primary key can't be made invisible.

Symptom → cause → fix

Symptom Likely cause Fix
Estimated rows far below actual on one table Stale or under-sampled statistics ANALYZE TABLE, raise STATS_SAMPLE_PAGES
Bad join order with a skewed filter Selectivity guessed on a non-indexed column Histogram on that column
Plan changes when the IN list grows eq_range_index_dive_limit crossed Smaller batches, or better statistics
Good plan on the replica, bad on the primary Different statistics samples ANALYZE TABLE on both, persistent statistics
Index ignored, "cost" in the trace Low selectivity, or a covering alternative Composite or covering index, or rewrite

Prevent it next time

  • Capture EXPLAIN FORMAT=TREE for your top queries in CI against a production-sized dataset, and diff them across releases and MySQL upgrades.
  • Schedule histogram refreshes for skewed columns after bulk loads.
  • Keep a short list of hinted queries and review it after every major version upgrade.