// SQL snippet

Find sort-heavy queries in MySQL

Sorting is work an index could have done ahead of time. This finds the queries sorting the most rows and spilling the most.

Main statement
MySQL

The task

MySQL sorts (EXPLAIN shows Using filesort) when an ORDER BY, or a GROUP BY that needs ordering, cannot read rows in order from an index. The digest table counts rows sorted per statement pattern, plus sort merge passes: when the rows do not fit in sort_buffer_size, MySQL writes sorted chunks to temporary files and merges them, and each merge round counts as a pass. A digest with many merge passes sorts a lot of data often, which is what a matching index removes.

The snippet

Written for MySQL.

MySQL
SELECT SCHEMA_NAME,
       COUNT_STAR AS calls,
       SUM_SORT_ROWS AS rows_sorted,
       SUM_SORT_SCAN AS full_sort_scans,
       SUM_SORT_MERGE_PASSES AS merge_passes,
       SUM_CREATED_TMP_DISK_TABLES AS on_disk_tmp,
       LEFT(DIGEST_TEXT, 120) AS digest
FROM performance_schema.events_statements_summary_by_digest
WHERE SUM_SORT_ROWS > 0
ORDER BY SUM_SORT_MERGE_PASSES DESC, SUM_SORT_ROWS DESC
LIMIT 20;

Fonctionnement

events_statements_summary_by_digest keeps one row per normalized statement per schema. SUM_SORT_ROWS totals rows sorted, SUM_SORT_SCAN counts sorts fed by a full table scan, and SUM_SORT_MERGE_PASSES counts merge rounds for sorts that overflowed sort_buffer_size. SUM_CREATED_TMP_DISK_TABLES is listed beside them because GROUP BY, DISTINCT and UNION often build an internal temporary table, and one that outgrows memory goes to disk. Merge passes lead the ordering because they mean the sort went to disk. The digest text has its literals replaced by ?; the variant reads events_statements_history, which keeps the last 10 statements of each connected thread with their real text, so it finds spilling sorts only from sessions that are still connected. Do not look for a sorting state in the processlist: on MySQL 8.4 a sorting query shows the state executing. The usual fix is an index with the WHERE equality columns first and the ORDER BY columns after them.

Variations

Recent statements whose sort spilled, with their literal text

SELECT t.PROCESSLIST_ID, t.PROCESSLIST_USER,
       h.SORT_ROWS, h.SORT_MERGE_PASSES,
       ROUND(h.TIMER_WAIT / 1e9, 1) AS ms,
       LEFT(h.SQL_TEXT, 120) AS query
FROM performance_schema.events_statements_history h
JOIN performance_schema.threads t ON t.THREAD_ID = h.THREAD_ID
WHERE h.SORT_MERGE_PASSES > 0
ORDER BY h.SORT_MERGE_PASSES DESC
LIMIT 20;

Questions that come up

What index satisfies WHERE status = 'paid' ORDER BY created_at DESC?

An index on (status, created_at): the equality column first, then the sort column. MySQL can read the index backwards for DESC, and since 8.0 you can also declare (status, created_at DESC). Either way the rows come out in final order and EXPLAIN no longer shows Using filesort.

Should I raise sort_buffer_size instead?

Raising it reduces merge passes, but the buffer is allocated per sort, per session, so a large global value multiplies across every connection that sorts. Sorting a million rows also stays expensive in memory. Fix the access path with an index first, and raise sort_buffer_size for a session (SET SESSION sort_buffer_size = ...) only for sorts that cannot be avoided.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.