When a database is slow, the instinct is to look for the slowest query. That is usually the wrong list. A report that takes eight seconds and runs twice a day costs you sixteen seconds of database time. A lookup that takes four milliseconds and runs two thousand times a second costs you eight seconds of database time every second. The second one is what is pinning your CPU.
The right ranking is by total time: how much of the server's work each kind of query consumes. This post shows how to get that ranking from MySQL, MariaDB and PostgreSQL with built-in tools, how to read the result, and what to do next.
Digests, not statements
SELECT * FROM orders WHERE id = 1001 and SELECT * FROM orders WHERE id = 1002 are the same query for tuning purposes. Both engines group them by replacing literals with placeholders and hashing the result. That grouped form is called a digest in MySQL and a queryid in PostgreSQL. Everything below works on those groups.
MySQL and MariaDB: performance_schema
The statement digest summary lives in performance_schema. It is on by default in MySQL and can be enabled in MariaDB with performance_schema = ON in the configuration, which needs a restart.
SELECT schema_name,
LEFT(digest_text, 80) AS query,
count_star AS calls,
ROUND(sum_timer_wait / 1e12, 2) AS total_s,
ROUND(avg_timer_wait / 1e9, 2) AS avg_ms,
sum_rows_examined AS rows_examined,
sum_rows_sent AS rows_sent
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC
LIMIT 10;Timers in performance_schema are in picoseconds, which is why the divisors look odd. The numbers accumulate since the server started or since the table was last reset, so a query that was a problem last month can still top the list. To measure a specific window, truncate the table, wait, and read it again:
TRUNCATE TABLE performance_schema.events_statements_summary_by_digest;PostgreSQL: pg_stat_statements
PostgreSQL needs an extension. It must be preloaded, which means a restart, and then created in the database you want to inspect:
# postgresql.conf
shared_preload_libraries = 'pg_stat_statements'CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT queryid,
calls,
ROUND(total_exec_time::numeric, 1) AS total_ms,
ROUND(mean_exec_time::numeric, 2) AS mean_ms,
rows,
shared_blks_hit + shared_blks_read AS blocks_touched,
LEFT(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;The column names above are for PostgreSQL 13 and later. Earlier versions call it total_time. On a Patroni cluster, remember that shared_preload_libraries is part of the cluster configuration, so change it through Patroni and plan a rolling restart instead of editing one node's postgresql.conf.
Reading the result
Look at three things together, not one.
- Total time. This is the ranking. The top three or four digests usually account for most of the load. Fixing them matters. Fixing the tenth does not.
- Rows examined versus rows returned. If a query examines 200,000 rows to return 20, it is almost always missing an index, or the index it has is not selective for the predicate. In MySQL this is
sum_rows_examinedagainstsum_rows_sent. In PostgreSQL,blocks_touchedper call plays the same role. - Calls. A cheap query called far too often is an application problem, such as an N+1 pattern, and no index will fix it.
Explain before you change anything
Once you have a candidate, look at its plan:
EXPLAIN SELECT * FROM orders WHERE customer_id = 4711 ORDER BY created_at DESC LIMIT 20;What to look for:
- A full table scan on a large table where you expected an index lookup.
- A filesort or a temporary table in MySQL, which means sorting or grouping without index support.
- In PostgreSQL, a large gap between estimated and actual rows. That points to stale statistics, and
ANALYZEis the first thing to try. - A sequential scan that PostgreSQL chose because the predicate matches a large fraction of the table. That can be correct.
EXPLAIN ANALYZE in PostgreSQL goes further and shows real timings, but it actually executes the statement. Never run it on an UPDATE or DELETE against production without wrapping it in a transaction you roll back, and be careful with long-running SELECT statements too.
Prove the fix worked
The step people skip is measuring afterwards. Add the index, wait until you have a meaningful number of executions, and compare the same digest's average time and rows examined before and after. If you cannot show it improved, you did not fix it. You changed something. For MySQL and MariaDB, build the index with an online schema change tool so the table is not locked for the duration. In PostgreSQL, use CREATE INDEX CONCURRENTLY.
How this looks in Jarwis ClusterOps
Query Analytics, under Observability, does the ranking for you. The agent on each database node reads the engine's own statistics about once a minute: performance_schema digests for MySQL, MariaDB and Galera, pg_stat_statements for PostgreSQL, and the equivalent sources for MongoDB and ClickHouse. Nothing extra is installed on your database. On PostgreSQL, Jarwis sets up pg_stat_statements on install and import where it can, and the Extensions tab manages it afterwards; a change that needs a rolling restart waits for an administrator's approval.
You can switch the window between 1 hour, 6 hours, 24 hours and 7 days, filter by schema, user or a regular expression on the digest text, and rank by load, latency or count. Each digest shows the rows examined per execution, and the previous-window toggle shows how it changed against the equal-length period before. Each digest that can have a plan has an EXPLAIN button and a Plan view with a cost tree and badges for full scans, filesorts, temporary tables and estimates that are far off. Plans only run on single read-only statements, and EXPLAIN ANALYZE for PostgreSQL is limited to administrators and asks for confirmation first. When you apply an index or an online schema change from the Schema tab, Jarwis compares latency and rows examined before and after and shows the result as an impact report, or tells you there is not enough data yet. On Pro, each digest also has an AI button that suggests indexes from the statistics and plan; it only shows text you can copy and never applies anything.
Lite is free up to three nodes and includes Query Analytics. You can click through it on the read-only demo at demo.jarwis.com. The reference is in the Query Analytics docs, with the schema and index side in Advisor and optimization.