Query Planning & EXPLAIN
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
MySQL decides how to run a query: which index to use for each table, in what order to join the tables, and
which join algorithm to apply. The decision is made by a cost-based optimizer from statistics, and EXPLAIN
shows the result. This page teaches how to read a plan, how the optimizer’s inputs (statistics, histograms,
hints) influence it, and how to find the statements worth analysing in the first place. The general method for a
slow query is in Diagnosing Slow Queries; index design is on
Indexing. Everything here ran on MySQL 26.10.0, on the shop schema and on the
generated tables from the Indexing page.
EXPLAIN output formats
EXPLAIN takes a statement and prints its plan without running it. The format is chosen with FORMAT= or the
explain_format variable. On the server used here explain_format defaults to TREE:
SELECT @@explain_format;
+------------------+
| @@explain_format |
+------------------+
| TREE |
+------------------+
so a bare EXPLAIN prints an indented tree. Older versions (and the same server with
SET explain_format = TRADITIONAL) print the tabular form with one row per table. Both describe the same plan.
The tabular form
SET explain_format = TRADITIONAL;
EXPLAIN SELECT c.name, o.id, i.sku, i.qty
FROM customers c JOIN orders o ON o.customer_id = c.id JOIN order_items i ON i.order_id = o.id
WHERE c.city = 'London';
+----+-------------+-------+------------+------+----------------------------+--------------------+---------+-----------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+----------------------------+--------------------+---------+-----------+------+----------+-------------+
| 1 | SIMPLE | c | NULL | ALL | PRIMARY | NULL | NULL | NULL | 4 | 25.00 | Using where |
| 1 | SIMPLE | o | NULL | ref | PRIMARY,fk_orders_customer | fk_orders_customer | 42 | shop.c.id | 2 | 100.00 | Using index |
| 1 | SIMPLE | i | NULL | ref | PRIMARY | PRIMARY | 4 | shop.o.id | 1 | 100.00 | NULL |
+----+-------------+-------+------------+------+----------------------------+--------------------+---------+-----------+------+----------+-------------+
Read the rows top to bottom: the first row is the first table read (the outer loop), and each next row is probed once per row of the previous ones. The columns:
| Column | Meaning |
|---|---|
|
The |
|
Table or alias (or |
|
The access type, from best to worst below |
|
Indexes the optimizer could use |
|
The index it chose and how many bytes of it are used (shows how many columns of a composite index are used) |
|
What is compared with the index ( |
|
The estimated number of rows it expects to read from this table for each probe |
|
The estimated percentage of those rows that survive the remaining |
|
Notes: |
The estimated number of rows flowing into the next table is rows × filtered / 100 of this one. In the plan above,
customers is scanned (4 rows, 25% survive city = 'London', so about 1 row), and each of those is probed in
orders through fk_orders_customer, then order_items through its primary key.
type is the most telling column. From best to worst:
type |
Meaning |
|---|---|
|
At most one row, found by primary key or unique index with a constant: read once during planning |
|
One row per row of the previous tables, through a primary or unique key (the typical join to a parent) |
|
Several rows through a non-unique index (or the leftmost prefix of one) |
|
An index range: |
|
A full scan of an index (smaller than the table, and |
|
A full table scan |
Frequent Extra values: Using index means a covering index; Using filesort means an extra sort pass because no
index delivers the order (the name is misleading: the sort happens in memory when it fits);
Using temporary means an internal temporary table for GROUP BY, DISTINCT or a derived table;
Using index condition is index condition pushdown (a filter evaluated inside the storage engine on the index
entry). Using where only says that a filter is applied on rows after they were read.
FORMAT=TREE
The tree format shows the plan as the executor will run it, with a cost and an estimated row count at every node, which makes join order and join algorithm explicit:
EXPLAIN FORMAT=TREE
SELECT c.name, o.id, i.sku, i.qty
FROM customers c JOIN orders o ON o.customer_id = c.id JOIN order_items i ON i.order_id = o.id
WHERE c.city = 'London';
-> Nested loop inner join (cost=4.88 rows=2.75)
-> Nested loop inner join (cost=2.61 rows=2)
-> Filter: (c.city = 'London') (cost=1.4 rows=1)
-> Table scan on c (cost=1.4 rows=4)
-> Covering index lookup on o using fk_orders_customer (customer_id = c.id) (cost=1.21 rows=2)
-> Index lookup on i using PRIMARY (order_id = o.id) (cost=1.07 rows=1.38)
A node’s children are evaluated inside it: the innermost nested loop joins c to o, and its result is joined to i.
Costs are in arbitrary optimizer units; compare them only with each other.
FORMAT=JSON
FORMAT=JSON returns the same information as a document for tools. In 26.10 it carries
"json_schema_version": "2.1" and uses the layout controlled by explain_json_format_version (2 here), a nested
inputs structure with operation, access_type, estimated_rows and estimated_total_cost. Setting
explain_json_format_version = 1 restores the older query_block layout with cost_info, used_key_parts and
rows_examined_per_scan, which was verified on this server:
EXPLAIN FORMAT=JSON SELECT * FROM orders WHERE customer_id = 'c-1';
{
"query": "/* select#1 */ select ... from `shop`.`orders` where (`shop`.`orders`.`customer_id` = 'c-1')",
"query_plan": {
"inputs": [
{
"operation": "Table scan on orders",
"table_name": "orders",
"access_type": "table",
"schema_name": "shop",
"used_columns": ["id", "customer_id", "status", "order_date"],
"estimated_rows": 8.0,
"estimated_total_cost": 1.8
}
],
"condition": "(orders.customer_id = 'c-1')",
"operation": "Filter: (orders.customer_id = 'c-1')",
"access_type": "filter",
"estimated_rows": 3.0,
"filter_columns": ["shop.orders.customer_id"],
"estimated_total_cost": 1.8
},
"query_type": "select",
"json_schema_version": "2.1"
}
(The used_columns array is reformatted onto one line and the query text shortened.) Tools written for the
older query_block layout need the version-1 setting or an update. For a table this small
(8 rows) the optimizer rightly prefers a table scan to the index.
EXPLAIN ANALYZE
EXPLAIN shows estimates; EXPLAIN ANALYZE executes the statement and adds measured values to each node:
actual time (milliseconds to the first row..all rows), rows and loops. The comparison between rows= in the
estimate and in the measurement is the first thing to check:
EXPLAIN ANALYZE
SELECT c.name, SUM(i.qty*i.price) total
FROM customers c JOIN orders o ON o.customer_id = c.id JOIN order_items i ON i.order_id = o.id
GROUP BY c.name;
-> Table scan on <temporary> (actual time=0.308..0.309 rows=4 loops=1)
-> Aggregate using temporary table (actual time=0.308..0.308 rows=4 loops=1)
-> Nested loop inner join (cost=12.3 rows=11) (actual time=0.276..0.289 rows=11 loops=1)
-> Nested loop inner join (cost=3.21 rows=8) (actual time=0.178..0.184 rows=8 loops=1)
-> Table scan on c (cost=1.4 rows=4) (actual time=0.172..0.173 rows=4 loops=1)
-> Covering index lookup on o using fk_orders_customer (customer_id = c.id) (cost=0.301 rows=2) (actual time=0.00183..0.00222 rows=2 loops=4)
-> Index lookup on i using PRIMARY (order_id = o.id) (cost=1.02 rows=1.38) (actual time=0.0125..0.0127 rows=1.38 loops=8)
loops=4 on o says it was probed four times, once per customer;
loops=8 on i is once per order, and rows=1.38 is the average rows per probe. Because the statement really
runs, do not use EXPLAIN ANALYZE on a DELETE or a very expensive SELECT in production without thought. It
works for SELECT statements and for multi-table UPDATE and DELETE.
Join algorithms
For each join the executor uses one of two algorithms.
-
Nested loop join (including index nested loop): for each row of the outer table, look up the matching rows of the inner table, ideally through an index. This is what the shop plans above do. It is excellent when the outer side is small and the inner side has an index, and quadratic otherwise.
-
Hash join: read the smaller input into an in-memory hash table keyed on the join columns, then stream the other input and probe the table. It needs no index on the join columns. MySQL uses it automatically whenever a join has an equality condition and no usable index. The hash table is limited by
join_buffer_size; beyond that it spills to disk files.
Block nested loop (BNL) was the historical algorithm for a join with no index: it buffered a block of outer rows
in the join buffer and scanned the inner table once per block. Hash join replaced it as the default for unindexed
equi-joins, and the old block_nested_loop switch and BNL / NO_BNL hints now control whether hash joins are
used (the manual notes that hash joins are governed by the same switches). Seeing "Using join buffer (hash join)"
in Extra tells you the hash join was chosen.
A demonstration on 300,000 orders joined with 5,000 customers, with no index on the joined columns (the join condition is an expression, so no index could be used anyway):
EXPLAIN ANALYZE
SELECT c.region, COUNT(*) FROM ord_noidx o
JOIN cust_big c ON c.name = CONCAT('cust ', o.customer_id) GROUP BY c.region;
-> Table scan on <temporary> (actual time=181..181 rows=4 loops=1)
-> Aggregate using temporary table (actual time=181..181 rows=4 loops=1)
-> Inner hash join (c.`name` = concat('cust ',o.customer_id)) (cost=150e+6 rows=1.5e+9) (actual time=5.58..143 rows=300000 loops=1)
-> Table scan on o (cost=6.17 rows=299665) (actual time=2.87..44.8 rows=300000 loops=1)
-> Hash
-> Table scan on c (cost=515 rows=5000) (actual time=0.425..1.84 rows=5000 loops=1)
The small table c is hashed (the Hash child), the 300,000-row table is streamed past it, and the whole
statement took 181 ms. With hash joins disabled (SET SESSION optimizer_switch = 'block_nested_loop=off') the same
query has no efficient algorithm left and the optimizer falls back to a nested loop that re-scans o once for each
row of c, with an estimated cost of 151e+6:
-> Nested loop inner join (cost=151e+6 rows=1.5e+9)
-> Table scan on c (cost=504 rows=5000)
-> Filter: (c.`name` = concat('cust ',o.customer_id)) (cost=222 rows=299665)
-> Table scan on o (cost=222 rows=299665)
(Run with plain EXPLAIN, so there are no actual times; it is not worth executing.) When the join column does have
an index, an index nested loop is the natural choice: the same query joined on c.id = o.customer_id used a
single-row primary-key lookup on c for each of the 300,000 orders and ran in 208 ms in total, close to the hash
join here because c has only 5,000 rows. The nested loop scales with the number of rows probed and the hash
join with the size of both inputs, so give an important join an index and read actual time rather than guessing.
Statistics and histograms
The optimizer estimates rows and filtered from statistics:
-
Index statistics (cardinality per index prefix) are sampled by InnoDB and refreshed by
ANALYZE TABLE; see Indexing. They answer how many rows matchcustomer_id = Xfor indexed columns. -
Histograms describe the value distribution of columns that are not indexed (or whose distribution is skewed), so
WHEREfilters on them are estimated well. They never make a query faster on their own: they only improve the optimizer’s estimates, which changes join order and access paths.
The cust_big table has a vip column that is 'y' for 1% of the rows. With no statistics the optimizer
assumes 10% for an equality condition on an unindexed column:
EXPLAIN SELECT * FROM cust_big WHERE vip = 'y';
ANALYZE TABLE cust_big UPDATE HISTOGRAM ON vip, region WITH 16 BUCKETS;
EXPLAIN SELECT * FROM cust_big WHERE vip = 'y';
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | cust_big | NULL | ALL | NULL | NULL | NULL | NULL | 5000 | 10.00 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
+--------------+-----------+----------+---------------------------------------------------+
| Table | Op | Msg_type | Msg_text |
+--------------+-----------+----------+---------------------------------------------------+
| lab.cust_big | histogram | status | Histogram statistics created for column 'region'. |
| lab.cust_big | histogram | status | Histogram statistics created for column 'vip'. |
+--------------+-----------+----------+---------------------------------------------------+
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | cust_big | NULL | ALL | NULL | NULL | NULL | NULL | 5000 | 1.00 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
filtered dropped from 10.00 to 1.00, matching the data (50 of 5000 rows). The histogram itself is stored in
information_schema.column_statistics; with only two distinct values it is a singleton histogram (one bucket per
value, with cumulative frequency), shown here for vip, where n is 99% and y is the rest:
SELECT column_name, JSON_EXTRACT(histogram, '$."histogram-type"') AS htype,
JSON_EXTRACT(histogram, '$.buckets') AS buckets
FROM information_schema.column_statistics WHERE schema_name = 'lab' AND table_name = 'cust_big';
ANALYZE TABLE cust_big DROP HISTOGRAM ON vip, region;
| vip | "singleton" | [["base64:type254:bg==", 0.99], ["base64:type254:eQ==", 1.0]] |
| region | "singleton" | [["base64:type254:ZWFzdA==", 0.25], ["base64:type254:bm9ydGg=", 0.5], ["base64:type254:c291dGg=", 0.75], ["base64:type254:d2VzdA==", 1.0]] |
(bg== and eQ== are the base64 of n and y; the output is abridged to the two data rows.) With more distinct
values than buckets MySQL builds an equi-height histogram instead. Histograms are not updated automatically:
rerun UPDATE HISTOGRAM after the data distribution changes, and drop them with DROP HISTOGRAM. Do not build
them on indexed columns where an index dive already gives an accurate estimate, nor on columns that are never
filtered.
Hints
When the optimizer’s choice is wrong and statistics cannot fix it, you can steer it. Prefer fixing statistics or indexes first, because hints freeze a decision that may become wrong as the data grows.
Index hints name indexes in the FROM clause: USE INDEX (consider only these), FORCE INDEX (a table scan
is treated as very expensive) and IGNORE INDEX. Optimizer hints are /*+ ... */ comments right after
SELECT and apply to a query block or a table; they are the modern, finer-grained mechanism.
Take the composite index from the Indexing page. By default the optimizer uses the composite index for a query on
customer_id and status; an optimizer hint can exclude it:
EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42 AND status = 'open';
EXPLAIN SELECT /*+ NO_INDEX(big_orders idx_cust_status_created) */ *
FROM big_orders WHERE customer_id = 42 AND status = 'open';
EXPLAIN SELECT * FROM big_orders FORCE INDEX (idx_customer) WHERE customer_id = 42 AND status = 'open';
| possible_keys | key | key_len | ref | rows | filtered | Extra |
| idx_customer,idx_cust_status_created,idx_status_amount_desc | idx_cust_status_created | 46 | const,const | 20 | 100.00 | NULL |
| idx_customer,idx_status_amount_desc | idx_customer | 4 | const | 60 | 50.00 | Using where |
| idx_customer | idx_customer | 4 | const | 59 | 50.00 | Using where |
(Only the interesting columns of the three plans are shown.) With the composite index excluded, or the other index
forced, MySQL reads about 60 candidate rows through idx_customer and filters on status afterwards, three times
the work of the composite index’s 20 (the estimate is 59 or 60 depending on the statistics sample at that moment).
Other hints that come up:
-
/*+ JOIN_ORDER(o, c) */fixes the join order;STRAIGHT_JOINbetween tables does the same by syntax. A test withordersfirst made it the outerindexscan andcustomersaneq_reflookup, rather than the optimizer’s own choice of readingcustomersfirst. -
/*+ BNL(t1, t2) */and/*+ NO_BNL(t1, t2) */enable or disable hash/block joins for given tables. -
/*+ NO_MERGE(d) */and/*+ MERGE(d) */for derived tables and views. -
/*+ SET_VAR(sort_buffer_size=1048576) */sets a system variable for the duration of one statement; the testSELECT /*+ SET_VAR(sort_buffer_size=1048576) */ @@sort_buffer_sizereturned 1048576. This is a clean alternative toSET SESSIONfollowed by a reset. -
Hint syntax errors only raise a warning (
SHOW WARNINGS), so check that the plan actually changed.
optimizer_switch
optimizer_switch is a list of on/off flags for individual optimizer features, settable globally or per session. The
test server reported:
index_merge=on index_merge_union=on index_merge_sort_union=on
index_merge_intersection=on engine_condition_pushdown=on index_condition_pushdown=on
mrr=on mrr_cost_based=on block_nested_loop=on
batched_key_access=off materialization=on semijoin=on
loosescan=on firstmatch=on duplicateweedout=on
subquery_materialization_cost_based=on use_index_extensions=on condition_fanout_filter=on
derived_merge=on use_invisible_indexes=off skip_scan=on
hash_join=on subquery_to_derived=off prefer_ordering_index=on
hypergraph_optimizer=off derived_condition_pushdown=on hash_set_operations=on
(Reformatted from one comma-separated line.) Change one flag without touching the rest:
SET SESSION optimizer_switch = 'semijoin=off';. Note hypergraph_optimizer=off: MySQL ships an alternative
optimizer implementation that is off here and is for experimentation, not production. Use these switches to
diagnose ("does the plan change if I turn this off?"), then fix the cause rather than leaving a global switch
changed.
Subqueries, derived tables and CTEs
MySQL rewrites subqueries into forms it can plan well. For an IN subquery it converts to a semijoin and then
chooses a strategy (FirstMatch, LooseScan, materialisation or duplicate weedout):
EXPLAIN FORMAT=TREE SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = 'open');
SET SESSION optimizer_switch = 'semijoin=off';
EXPLAIN SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = 'open');
-> Hash semijoin (FirstMatch) (orders.customer_id = customers.id) (cost=2.56 rows=0.5)
-> Table scan on customers (cost=0.65 rows=4)
-> Hash
-> Filter: (orders.`status` = 'open') (cost=0.453 rows=1)
-> Table scan on orders (cost=0.453 rows=8)
+----+-------------+-----------+------------+----------+--------------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-----------+------------+----------+--------------------+------+---------+------+------+----------+-------------+
| 1 | PRIMARY | customers | NULL | ALL | NULL | NULL | NULL | NULL | 4 | 100.00 | Using where |
| 2 | SUBQUERY | orders | NULL | ALL | fk_orders_customer | NULL | NULL | NULL | 8 | 12.50 | Using where |
+----+-------------+-----------+------------+----------+--------------------+------+---------+------+------+----------+-------------+
With the semijoin transformation the subquery became a single Hash semijoin step; with it off the plan reports a
separate SUBQUERY evaluated as a subquery. NOT EXISTS (or NOT IN) becomes an antijoin; the plan for
customers without orders showed Not exists in Extra and used the foreign-key index:
EXPLAIN SELECT name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
| 1 | SIMPLE | c | NULL | ALL | NULL | NULL | NULL | NULL | 4 | 100.00 | NULL |
| 1 | SIMPLE | o | NULL | ref | fk_orders_customer | fk_orders_customer | 42 | shop.c.id | 2 | 100.00 | Using where; Not exists; Using index |
Derived tables and views (FROM (SELECT ...) d) are merged into the outer query when possible
(derived_merge=on), so the optimizer sees one query. When the derived table cannot be merged (it uses GROUP BY,
DISTINCT, LIMIT or aggregates) or merging is disabled, it is materialised into a temporary table, shown as
<derived2> with a DERIVED row:
EXPLAIN SELECT * FROM (SELECT customer_id, COUNT(*) n FROM orders GROUP BY customer_id) d WHERE d.n > 1;
EXPLAIN SELECT * FROM (SELECT * FROM orders WHERE status='open') d WHERE d.id > 1003;
| 1 | PRIMARY | <derived2> | NULL | ALL | NULL | NULL | NULL | NULL | 8 | 100.00 | NULL |
| 2 | DERIVED | orders | NULL | index | fk_orders_customer | fk_orders_customer | 42 | NULL | 8 | 100.00 | Using index |
| 1 | SIMPLE | orders | NULL | range | PRIMARY | PRIMARY | 4 | NULL | 5 | 12.50 | Using where |
The first query has to materialise the aggregate; the second was merged away and shows only a SIMPLE read of
orders. A WITH clause (CTE) behaves like a derived table that can be referenced several times; if it is
referenced more than once it is materialised once and read many times (Materialize CTE t if needed and a lookup
on its <auto_key0>, an automatically created index on the temporary table).
The optimizer trace
When a plan is unexpected, the optimizer trace records every decision (cost of each access path, transformations, join orders considered) as JSON:
SET SESSION optimizer_trace = 'enabled=on';
SELECT c.name FROM customers c JOIN orders o ON o.customer_id = c.id WHERE o.status = 'open';
SELECT JSON_EXTRACT(trace, '$.steps[*].join_optimization.steps[*].considered_execution_plans[*].best_access_path.considered_access_paths[*].rows_to_scan') AS rows_to_scan
FROM information_schema.optimizer_trace;
SET SESSION optimizer_trace = 'enabled=off';
+--------------+
| rows_to_scan |
+--------------+
| [4, 8] |
+--------------+
The trace for the last statement of the session is in information_schema.optimizer_trace; it begins with a
join_preparation step showing the expanded query and the transformations applied. It is verbose and is meant for
occasional deep dives; enable it only for the session and statement you are studying.
Finding the queries to analyse
The slow query log
The slow query log records statements slower than long_query_time (10 s by default) and optionally those that
use no index. It is off by default and written to a file (log_output = FILE):
SELECT @@slow_query_log, @@long_query_time, @@slow_query_log_file, @@log_output,
@@log_queries_not_using_indexes, @@min_examined_row_limit;
SET GLOBAL slow_query_log = ON;
SET GLOBAL log_slow_extra = ON;
SET SESSION long_query_time = 0.02;
SELECT COUNT(*), SUM(amount) FROM lab.big_orders WHERE note LIKE '%99%';
SET GLOBAL slow_query_log = OFF;
SET GLOBAL log_slow_extra = OFF;
@@slow_query_log 0 @@long_query_time 10.000000 @@slow_query_log_file /var/lib/mysql/88723d43925d-slow.log
@@log_output FILE @@log_queries_not_using_indexes 0 @@min_examined_row_limit 0
The file then holds an entry such as this (trimmed):
# Time: 2026-11-10T19:07:51.790284Z
# User@Host: root[root] @ localhost [] Id: 56
# Query_time: 0.029754 Lock_time: 0.000001 Rows_sent: 1 Rows_examined: 300000 Thread_id: 56 Errno: 0 ...
SET timestamp=1794337671;
select count(*), sum(amount) from lab.big_orders where note like '%99%';
The key figures are Query_time, Lock_time and the ratio of Rows_examined to Rows_sent (300,000 to 1: a
scan). log_slow_extra adds the extra fields shown. Two details trip people up: SET GLOBAL long_query_time
affects only new connections, so in a running session also SET SESSION long_query_time; and the log files are
raw text, summarised with mysqldumpslow or a tool such as Percona’s pt-query-digest rather than by eye. Keep
long_query_time at a sensible value in production and enable log_queries_not_using_indexes only temporarily:
it is noisy.
performance_schema statement digests
performance_schema aggregates all statements by digest (the normalised text with literals replaced), in memory
and without a log file. It is the first stop for "which queries cost the most":
SELECT schema_name, LEFT(digest_text,70) AS digest_text, count_star,
ROUND(sum_timer_wait/1e9,1) AS total_ms, ROUND(avg_timer_wait/1e9,2) AS avg_ms,
sum_rows_examined, sum_rows_sent, sum_no_index_used
FROM performance_schema.events_statements_summary_by_digest
WHERE schema_name = 'lab' ORDER BY sum_timer_wait DESC LIMIT 3;
+-------------+------------------------------------------------------------------------+------------+----------+---------+-------------------+---------------+-------------------+
| schema_name | digest_text | count_star | total_ms | avg_ms | sum_rows_examined | sum_rows_sent | sum_no_index_used |
+-------------+------------------------------------------------------------------------+------------+----------+---------+-------------------+---------------+-------------------+
| lab | INSERT INTO `pk_uuid_text` ( `id` , `payload` ) WITH RECURSIVE `s` ( ` | 1 | 1585.8 | 1585.79 | 500000 | 0 | 1 |
| lab | INSERT INTO `pk_uuid_bin` ( `id` , `payload` ) WITH RECURSIVE `s` ( ` | 1 | 1316.4 | 1316.37 | 500000 | 0 | 1 |
| lab | INSERT INTO `pk_auto` ( `payload` ) WITH RECURSIVE `s` ( `n` ) AS ( SE | 1 | 856.5 | 856.53 | 500000 | 0 | 1 |
+-------------+------------------------------------------------------------------------+------------+----------+---------+-------------------+---------------+-------------------+
Columns to look at are the total and average time, sum_rows_examined versus sum_rows_sent (a large ratio
means wasted reads) and sum_no_index_used. The sys schema wraps the same data in readable views:
sys.statement_analysis (ordered by total latency, with rows_examined_avg and a full_scan flag) and
sys.statements_with_full_table_scans. Counters reset at restart, or on demand with
TRUNCATE TABLE performance_schema.events_statements_summary_by_digest. Combine a digest with EXPLAIN on a
representative literal version of the statement to find out why it is expensive. Monitoring with
performance_schema and sys more broadly is on Administration, and
the general tuning workflow on Performance Tuning.
Related
-
Indexing — the access paths the optimizer chooses between.
-
Diagnosing Slow Queries — the engine-neutral workflow.
-
Pagination Strategies — plans for
OFFSETversus keyset paging. -
PostgreSQL Reference — the equivalent
EXPLAINmodel in PostgreSQL.