dataiotech Labs
Back to Performance Guide
[MySQL]RUNBOOKMySQL 8.4 LTS / 8.022 minSenior DBA / SRE

[MySQL] RUNBOOK: Finding the 20 Most Expensive Queries with Performance Schema

What pg_stat_statements is in PostgreSQL, Performance Schema is in MySQL. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how to enable Performance Schema, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, and how to decide the fix. This article is the first cluster that starts the MySQL leg of the Performance Pillar.

Production Incident Scenario

Time is 11:42. The application team writes: Pages open in 8 seconds, yesterday it was 400 ms. CPU is at 90%, disk I/O is maxed out. The team says let's scale up the server. The DBA says stop, let's measure first. Because a deploy happened last night. Maybe a new query was added. Maybe an index was deleted. Maybe a JOIN broke. Scaling up by guess hides the problem. First we need to find which query is eating the system. This runbook shows what to do at that moment.

Summary

What pg_stat_statements is in PostgreSQL, Performance Schema is in MySQL. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how to enable Performance Schema, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, and how to decide the fix. This article is the first cluster that starts the MySQL leg of the Performance Pillar.

Scenario

Time is 11:42. The application team writes: Pages open in 8 seconds, yesterday it was 400 ms. CPU is at 90%, disk I/O is maxed out. The team says let's scale up the server. The DBA says stop, let's measure first. Because a deploy happened last night. Maybe a new query was added. Maybe an index was deleted. Maybe a JOIN broke. Scaling up by guess hides the problem. First we need to find which query is eating the system. This runbook shows what to do at that moment.

Concept: What Is Performance Schema?

Performance Schema is MySQL's internal measurement system. Which query ran how many times, how long it took in total, how many rows it read, how many temporary tables it created, how long it waited for locks — it records all of them.

What is done with the pg_stat_statements extension in PostgreSQL is done by Performance Schema in MySQL. But there is one difference: Performance Schema does not record everything by default. Some consumers are off. First you need to turn them on.

The 2 most important tables:

  • •events_statements_summary_by_digest: Summarizes queries in normalized form. So WHERE id = 123 and WHERE id = 456 count as the same query. This is the main table for finding the most expensive query.
  • •events_statements_current: Shows currently running queries. Used for lock and long-query diagnosis.

Step 0: Is Performance Schema On?

First check if it is on.

sql
SHOW VARIABLES LIKE 'performance_schema';

It should return ON. If it is off, turn it on in my.cnf and restart MySQL.

ini
[mysqld] performance_schema = ON

Then verify the required consumers are on:

sql
SELECT NAME, ENABLED FROM performance_schema.setup_consumers WHERE NAME LIKE '%statements%';

All of them should be YES. If not, turn them on:

sql
UPDATE performance_schema.setup_consumers SET ENABLED = 'YES' WHERE NAME LIKE '%statements%';

Also check that the sys schema is installed. The sys schema provides ready-made views that make Performance Schema queries easier.

sql
SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = 'sys';

If the result is 1, it is installed. If it is 0, you need to install the sys schema that comes with MySQL.

Step 1: Find the 20 Most Expensive Queries

This is the main query. It sorts by total time.

sql
SELECT LEFT(DIGEST_TEXT, 150) AS query_text, COUNT_STAR AS exec_count, ROUND(SUM_TIMER_WAIT / 1000000000000, 2) AS total_time_sec, ROUND(AVG_TIMER_WAIT / 1000000000000, 4) AS avg_time_sec, ROUND(MAX_TIMER_WAIT / 1000000000000, 4) AS max_time_sec, SUM_ROWS_SENT AS rows_sent, SUM_ROWS_EXAMINED AS rows_examined, SUM_CREATED_TMP_TABLES AS tmp_tables, SUM_NO_INDEX_USED AS no_index_count, SUM_ERRORS AS error_count FROM performance_schema.events_statements_summary_by_digest WHERE DIGEST_TEXT IS NOT NULL ORDER BY SUM_TIMER_WAIT DESC LIMIT 20;

▸How to Read the Output?

  • •total_time_sec: This is the query that tires the system the most. Look at this first.
  • •avg_time_sec: If a single query is fast but runs many times, it may be N+1. Low average, high total means N+1 suspicion.
  • •rows_examined / rows_sent: If the ratio is over 100, the query reads unnecessary rows. The index may be missing or wrong.
  • •no_index_count: If greater than 0, the query ran without an index. Urgent review needed.
  • •tmp_tables: If high, the query creates temporary tables for GROUP BY, ORDER BY, or DISTINCT. It can be fixed with tmp_table_size and indexes.

An easier way is to use the sys schema:

sql
SELECT LEFT(query, 150) AS query_text, exec_count, total_latency, avg_latency, rows_examined, rows_sent FROM sys.statements_with_runtimes_in_95th_percentile ORDER BY total_latency DESC LIMIT 20;

The sys schema automatically converts time units. You do not need to calculate picoseconds with SUM_TIMER_WAIT.

Step 2: Diagnose the Top 3 Queries Precisely

You found the 20 most expensive queries. Now focus on the top 3. Do not try to fix them all at once.

For each query, answer 3 questions:

▸Question 1: Is the Query Really Slow, or Does It Run Too Often?

Two different problems, two different solutions:

  • •Slow query: Average time is high, execution count is low. For example average 8 seconds, runs 100 times a day. Solution: Index, plan, query design.
  • •Frequent query: Average time is low, execution count is very high. For example average 8 ms, runs 2 million times a day. Solution: N+1 fix, cache, batch.

We made the same distinction in the PostgreSQL article. In MySQL the rule is the same.

▸Question 2: Is the Plan Bad?

sql
EXPLAIN FORMAT=TREE SELECT * FROM orders WHERE customer_id = 123 AND status = 'open';

In MySQL EXPLAIN output, look for these:

  • •type = ALL: Full table scan. Disaster on a large table.
  • •type = index: Index scan but reads the whole index. Selectivity may be low.
  • •type = ref: Search with index. Usually good.
  • •type = const: Single row. Best.
  • •rows: Estimated rows to read. If very different from actually read rows, statistics are old.
  • •Extra = Using filesort: Temporary file used for sorting. Can be fixed with an index.
  • •Extra = Using temporary: Temporary table created. Index needed for GROUP BY and ORDER BY.

For a more detailed plan:

sql
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123 AND status = 'open';

MySQL 8.0.18 and above support EXPLAIN ANALYZE. It shows real execution time and row count. Not an estimate, the truth.

▸Question 3: Does the Query Use an Index?

sql
SELECT OBJECT_SCHEMA AS database_name, OBJECT_NAME AS table_name, INDEX_NAME AS index_name, COUNT_FETCH AS fetch_count FROM performance_schema.table_io_waits_summary_by_index_usage WHERE OBJECT_SCHEMA NOT IN ('mysql', 'performance_schema', 'sys') ORDER BY COUNT_FETCH DESC LIMIT 20;

Find unused indexes too:

sql
SELECT OBJECT_SCHEMA AS database_name, OBJECT_NAME AS table_name, INDEX_NAME AS index_name FROM performance_schema.table_io_waits_summary_by_index_usage WHERE INDEX_NAME IS NOT NULL AND COUNT_FETCH = 0 AND OBJECT_SCHEMA NOT IN ('mysql', 'performance_schema', 'sys') ORDER BY OBJECT_NAME;

COUNT_FETCH = 0 means that index has never been used. But do not delete it immediately. First monitor for 30 days. It may be for a report that runs once a month.

Step 3: Look at Currently Running Queries

Past summary is not enough. Look at what is running now.

sql
SELECT THREAD_ID AS thread_id, USER AS user_name, LEFT(SQL_TEXT, 150) AS query_text, TIMER_WAIT / 1000000000000 AS time_sec, STATE AS state FROM performance_schema.events_statements_current WHERE SQL_TEXT IS NOT NULL ORDER BY TIMER_WAIT DESC LIMIT 20;

If a query has been running for 5 minutes, it may be locking the system right now. The past summary will show it in 5 minutes. But you must see it now.

Also check long transactions:

sql
SELECT trx_id, trx_state, trx_started, TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS time_sec, trx_query AS query_text FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 20;

If a transaction has been open for 10 minutes, it keeps locks open too. Close it first.

Step 4: Decide the Fix

Diagnosis is complete. Now decide. Choose 1 action per query. Do not do 3 actions at once.

▸Decision 1: Add an Index

If EXPLAIN output shows type = ALL and rows_examined / rows_sent ratio is high, add an index.

sql
-- First test in a test environment CREATE INDEX idx_orders_customer_status ON orders (customer_id, status); -- Then get the plan again EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123 AND status = 'open';

In MySQL, creating an index can lock the table. On a large table use ALGORITHM=INPLACE:

sql
ALTER TABLE orders ADD INDEX idx_orders_customer_status (customer_id, status), ALGORITHM=INPLACE, LOCK=NONE;

▸Decision 2: Fix the Query

If the query does SELECT * and only 3 columns are needed, fix the query.

sql
-- Bad: SELECT * FROM orders WHERE customer_id = 123; -- Good: SELECT id, total, created_at FROM orders WHERE customer_id = 123;

If the query uses a function-wrapped WHERE, fix it.

sql
-- Bad: Index is not used SELECT * FROM orders WHERE DATE(created_at) = '2026-11-30'; -- Good: Index is used SELECT * FROM orders WHERE created_at >= '2026-11-30' AND created_at < '2026-12-01';

▸Decision 3: Fix N+1

If the query averages 8 ms but runs 2 million times a day, there is N+1. Do not run queries in a loop. Fetch with a single JOIN.

sql
-- Bad: 100 queries in a loop -- SELECT * FROM orders WHERE user_id = ? -- Good: Single query SELECT u.id, u.name, o.id, o.total FROM users u LEFT JOIN orders o ON o.user_id = u.id;

▸Decision 4: Change Parameters — Last Resort

If the query is correct, the index is correct, but the system is still slow, then look at parameters. But parameters are not the first step, they are the last step. Buffer Pool and Redo Log settings will be covered in detail in the next cluster article.

Verification: Did the Fix Work?

Record the baseline measurement before the fix. Measure the same query again after the fix.

sql
SELECT LEFT(DIGEST_TEXT, 150) AS query_text, COUNT_STAR AS exec_count, ROUND(SUM_TIMER_WAIT / 1000000000000, 2) AS total_time_sec, ROUND(AVG_TIMER_WAIT / 1000000000000, 4) AS avg_time_sec FROM performance_schema.events_statements_summary_by_digest WHERE DIGEST_TEXT LIKE '%orders%' ORDER BY SUM_TIMER_WAIT DESC LIMIT 10;

Success criteria:

  • •Did total time drop?
  • •Did average time drop?
  • •Did examined / sent ratio drop?
  • •Did no-index execution count go to zero?

If you cannot say yes to these questions, the fix did not work. Revert it, diagnose again.

7 Common Mistakes

First mistake: Adding an index by guess without enabling Performance Schema. Do not change without measuring.

Second mistake: Choosing the most expensive query by average time. What tires the system is total time. Low average but high total means N+1.

Third mistake: Moving unnecessary columns with SELECT *. Moving 3 columns instead of 20 reduces I/O and network traffic.

Fourth mistake: Using a function-wrapped WHERE. DATE(created_at) kills the index. Use a range.

Fifth mistake: Not deleting unused indexes. Every unused index slows every write.

Sixth mistake: Settling for past summary and not looking at currently running queries. The past shows 5 minutes ago. The currently running query shows the crisis.

Seventh mistake: Trying to fix a bad query by changing parameters. First fix the query, then look at parameters.

Checklist

  • Performance Schema is on checked
  • Consumers are on checked
  • sys schema is installed checked
  • 20 most expensive queries listed by total time
  • Top 3 queries diagnosed precisely
  • Slow query vs frequent query distinction made
  • Plan obtained with EXPLAIN ANALYZE
  • Index usage checked
  • Currently running queries checked
  • Long transaction existence checked
  • 1 fix action chosen, not all at once
  • Index tested in test environment first
  • ALGORITHM=INPLACE used on large tables
  • Total and average time measured again after fix
  • Useless fix reverted

Conclusion

In MySQL, as in PostgreSQL, performance problems start with measurement. Performance Schema is the mirror of the system. First look in the mirror, then fix. Adding an index by guess, scaling up a server by guess, hides the problem but does not solve it.

Next cluster: InnoDB Buffer Pool and Redo Log Tuning. Because after finding the most expensive query, next is to set memory and write log correctly.

Related Articles

  • •Pillar: Performance Guide — Performance & Query Optimization
  • •Cluster: [PostgreSQL] Finding the 20 Most Expensive Queries with pg_stat_statements
  • •Cluster: [Universal] N+1 Query Problem and Connection Pool Relationship
  • •Cluster: [Universal] EXPLAIN ANALYZE Reading Guide
  • •Cluster: [Universal] Partitioning Blueprint
  • •Next: [MySQL] InnoDB Buffer Pool and Redo Log Tuning
Operational Checklist

Verify each operational safety check before completing the task: