Quickly Find the Highest CPU‑Consuming SQL in MySQL
This guide explains how to pinpoint the MySQL statements that use the most CPU by mapping OS thread IDs to MySQL sessions, querying performance_schema and information_schema, and reviewing the execution plan to identify optimization opportunities.
Overview
If you need to locate the SQL statements that are driving the highest CPU usage in a MySQL database, you can use the THREAD_OS_ID column added to performance_schema.threads (available from MySQL 5.7) together with OS‑level monitoring tools. The method works for cases where a specific CPU core is overloaded by database queries.
Identify the OS threads consuming CPU
Run pidstat -t -p <mysqld_pid> 1 5 to sample the MySQL server process. The output lists thread IDs (e.g., 802, 4445) that are using significant CPU time. Verify that the high‑CPU usage is consistent across multiple samples.
Map the OS thread to a MySQL session
SELECT * FROM performance_schema.threads WHERE thread_os_id = <thread_id>;
SELECT * FROM information_schema.`PROCESSLIST` WHERE id = threads.processlist_id;The first query finds the MySQL thread that corresponds to the OS thread ID; the second query retrieves the SQL statement associated with that MySQL thread.
Examine the execution plan
Run EXPLAIN FORMAT=JSON <problematic_sql>; (or use the GUI “Explain” feature) to view the execution plan. The plan reveals why the query is CPU‑intensive, often due to missing indexes.
In most cases, creating an appropriate index on the involved columns resolves the high CPU consumption.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
