MySQL Query Optimization Patterns and the Slow Query Log

MySQL 65 min min read Updated: Nov 27, 2026 Advanced
MySQL Query Optimization Patterns and the Slow Query Log
Advanced Topic 3 of 3

Measure First

Optimize the queries that matter: the slowest, or the fastest ones run thousands of times. The slow query log records statements that take longer than long_query_time.

sql SET GLOBAL slow_query_log = 'ON'; SET GLOBAL long_query_time = 1; -- seconds SET GLOBAL log_queries_not_using_indexes = 'ON'; SHOW VARIABLES LIKE 'slow_query_log_file';

Summarize the log with mysqldumpslow -s t /path/to/slow.log (shows the worst queries by total time) or pt-query-digest from Percona Toolkit. These commands change server settings and read a log file, so they are shown but not run here.

See Slow Statements with the sys Schema

MySQL 8 ships the sys schema, built on performance_schema. Statements are grouped by their normalized form:

sql SELECT query, exec_count, total_latency, rows_examined_avg FROM sys.statement_analysis ORDER BY total_latency DESC LIMIT 5; SELECT * FROM sys.schema_unused_indexes; SELECT * FROM sys.schema_redundant_indexes;

Check that the views exist on any server:

sql SELECT COUNT(*) > 0 AS sys_schema_present FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'sys' AND TABLE_NAME = 'statement_analysis';

Result:

sys_schema_present
1

Pattern 1: Select Only What You Need

SELECT * reads and sends every column, defeats covering indexes, and breaks when columns are added. Name the columns.

sql EXPLAIN SELECT * FROM big_users WHERE country = 'US' AND created = '2024-05-01';

MySQL plan:

tabletypekeyrowsExtra
big_usersrefidx_big_country_created55NULL
sql EXPLAIN SELECT country, created FROM big_users WHERE country = 'US' AND created = '2024-05-01';

MySQL plan:

tabletypekeyrowsExtra
big_usersrefidx_big_country_created55Using index

The second plan can show Using index: no table rows are read.

Pattern 2: Keyset Pagination

LIMIT 20 OFFSET 19980 still reads and throws away 19,980 rows. Remember the last id and continue after it:

sql SELECT id FROM (SELECT id FROM products ORDER BY id) t WHERE id > 5 ORDER BY id LIMIT 3;

Result:

id
6
7
8
sql EXPLAIN SELECT id, email FROM big_users WHERE id > 19980 ORDER BY id LIMIT 20;

MySQL plan:

tabletypekeyrowsExtra
big_usersrangePRIMARY20Using where
sql -- page 2 onward: pass the last id from the previous page SELECT id, email FROM big_users WHERE id > :last_seen_id ORDER BY id LIMIT 20;

The cost stays small on every page. The trade-off is that you cannot jump to page 500 directly.

Pattern 3: Avoid Functions on Indexed Columns

sql EXPLAIN SELECT id FROM big_users WHERE DATE_ADD(created, INTERVAL 1 DAY) = '2024-03-02';

MySQL plan:

tabletypekeyrowsExtra
big_usersindexidx_big_created20216Using where; Using index
sql EXPLAIN SELECT id FROM big_users WHERE created = DATE_SUB('2024-03-02', INTERVAL 1 DAY);

MySQL plan:

tabletypekeyrowsExtra
big_usersrefidx_big_created55Using index

Pattern 4: Count Smartly

COUNT(*) on a big InnoDB table must count rows, because of MVCC. If an approximation is enough, use the statistics:

sql SELECT TABLE_ROWS > 0 AS has_estimate FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'orders';

Result:

has_estimate
1

TABLE_ROWS is an estimate for InnoDB. Use it for "about 20,000 rows" displays, and exact COUNT(*) where precision matters.

Pattern 5: Batch Writes

Insert many rows per statement or per transaction. Updating a million rows in one go creates a huge transaction. Work in chunks:

sql -- repeat until 0 rows affected DELETE FROM big_logs WHERE created < '2024-01-01' LIMIT 5000;

Pattern 6: EXISTS Instead of Counting

sql EXPLAIN SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

MySQL plan:

tabletypekeyrowsExtra
cALLNULL6NULL
orefcustomer_id1Using index; FirstMatch(c)

Housekeeping

  • ANALYZE TABLE t; refreshes statistics so the optimizer chooses well.
  • OPTIMIZE TABLE t; rebuilds a table to reclaim space after huge deletes (it locks or copies the table, so schedule it).
  • Keep the InnoDB buffer pool large enough for the hot data. Check innodb_buffer_pool_size.
  • Match column types in joins and use the same character set and collation.
sql SELECT ROUND(@@innodb_buffer_pool_size / 1024 / 1024) AS buffer_pool_mb, @@long_query_time AS long_query_time_default;

Result:

buffer_pool_mblong_query_time_default
12810.0
Defaults vary Buffer pool size here is the small default of this test server. Production servers usually give 50-70% of RAM to it on a dedicated database host.

Common Beginner Mistakes

MistakeWhat happensFix
Optimizing without measuringWasted effortSlow log, sys.statement_analysis, EXPLAIN
Deep OFFSET paginationSlower every pageKeyset pagination
SELECT * everywhereWasted I/O, no covering indexSelect columns
Huge single transactionsLong locks, big undo logBatch
Ignoring the buffer pool sizeDisk reads on hot dataSize it for your data
Query cache advice from old blogsRemoved in MySQL 8.0Cache in the application

Practice

  1. Rewrite an OFFSET pagination query with keyset pagination.
  2. Find a query using a function on a column and rewrite it.
  3. Turn on the slow query log in a test server and capture a SLEEP(2) query.
  4. List unused indexes with the sys schema.

Conclusion

Measure with the slow log and sys, then fix: select fewer columns, use keyset pagination, keep indexed columns free of functions, batch big writes, and keep statistics fresh.

Quick Summary: slow query log, sys schema, keyset pagination, covering index, batching, ANALYZE TABLE.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators