Sub topic 5
Finding the queries that cost the most overall
This chapter assumes that pg_stat_statements is already enabled and that you know what calls, total_exec_time, mean_exec_time, and queryid mean. You should be comfortable with ORDER BY, LIMIT, aggregates, and window functions. The column names total_exec_time and mean_exec_time apply to PostgreSQL 13 and later. Older versions have a single total_time column.
Why rank by total time
A query that takes 2 ms and runs 40 million times a day uses more server time than a report that takes 30 seconds and runs once. The report is easy to notice because someone waits for it. The 2 ms query is invisible in a single execution, but it can dominate CPU and I/O.
total_exec_time is the sum of the execution time of every call to a normalized query since statistics were last reset. It is roughly calls * mean_exec_time. Sorting by it answers this question: if I made this one query disappear, how much load would I remove?
This is the best first ranking for general tuning. It points at the work that is worth optimizing, not the queries that merely look slow.
The basic ranking
This is the query from the earlier chapters, with the names written out so you can read each column:
SELECT queryid,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Read each row as a story:
- High
callsand lowmean_msmeans a frequent, cheap query. Savings usually come from running it less often (caching, batching, removing an N+1 pattern in the application) or from making an already small cost smaller. - Low
callsand highmean_msmeans a rare, expensive query. Savings usually come from a better plan, such as an index, a rewrite, or fresher planner statistics. rowsdivided bycallstells you how much each call returns. A very large value suggests the application fetches more than it needs.
Show each query's share of the total
Raw milliseconds are hard to judge. A query with 90 seconds of total time matters a lot on a server that accumulated 100 seconds, and very little on one that accumulated 100 hours. Add a percentage with a window function:
SELECT queryid,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
round((100 * total_exec_time
/ sum(total_exec_time) OVER ())::numeric, 1) AS pct_of_total,
round(mean_exec_time::numeric, 2) AS mean_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;The window function sum(...) OVER () is evaluated across every row before LIMIT is applied. The percentages are therefore shares of all recorded time, not shares of the ten rows shown.
Look at how the shares fall off:
- If the top query holds 40% and the next holds 5%, fix the first one and measure again.
- If the top ten each hold 2 to 3%, the load is spread out. No single fix helps much, and you should look for systemic causes such as missing statistics, a bad
work_mem, or connection churn.
Group by queryid across users and databases
pg_stat_statements keeps one row per combination of userid, dbid, and queryid (and, from PostgreSQL 14, a toplevel flag). The same application query run by two roles, or against two databases, appears as separate rows. Each row can look small while the combined cost is large.
To rank by the query itself, aggregate:
SELECT queryid,
sum(calls) AS calls,
round(sum(total_exec_time)::numeric, 2) AS total_ms,
round((sum(total_exec_time)
/ sum(calls))::numeric, 2) AS mean_ms,
count(DISTINCT dbid) AS databases,
min(left(query, 80)) AS query
FROM pg_stat_statements
GROUP BY queryid
ORDER BY sum(total_exec_time) DESC
LIMIT 10;Recompute the mean as sum(total_exec_time) / sum(calls). Averaging the per-row mean_exec_time values would weight a row with 3 calls the same as a row with 3 million.
Include planning time when it is tracked
total_exec_time covers execution only. Planning time is recorded separately in total_plan_time, and it stays at zero unless pg_stat_statements.track_planning is on. That setting is off by default because it adds overhead on very busy systems.
If you have enabled it, rank by the sum:
SELECT queryid,
calls,
round(total_plan_time::numeric, 2) AS plan_ms,
round(total_exec_time::numeric, 2) AS exec_ms,
round((total_plan_time + total_exec_time)::numeric, 2) AS total_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_plan_time + total_exec_time DESC
LIMIT 10;A large plan_ms compared with exec_ms means the planner spends longer deciding than the executor spends working. That happens with queries over many partitions or many joins, and it is a reason to consider prepared statements.
Keep the ranking honest
Several details change what the top of the list means.
- Your own monitoring queries appear in the list. Add
WHERE query NOT ILIKE '%pg_stat_statements%'while you explore. - Utility statements such as
COPY,VACUUM, and DDL are tracked only whenpg_stat_statements.track_utilityison, which is the default. A nightlyCOPYcan head the ranking. That is real time, but you tune it differently from an applicationSELECT. - Statements inside functions are counted separately only when
pg_stat_statements.trackisall. With the defaulttop, only the outermost call is recorded, and the function's inner statements are hidden inside its total time. Withall, the outer call's time already includes the inner statements, so summing every row double counts. Do not add the whole column and call it server time. - The ranking covers the whole accumulation period. A query that was heavy last month and has since been fixed can still sit near the top. If the list looks stale, reset and measure a defined window, as covered in the chapter on resetting statistics.
- Entries can be evicted when the number of distinct statements exceeds
pg_stat_statements.max. Evicted queries vanish from the ranking, and a heavy query that is evicted and re-created shows only its recent history.
From a ranking to a shortlist
Total time tells you what is expensive. It does not tell you why. Turn the top rows into a shortlist by pairing each with a hypothesis.
| Pattern in the row | Likely cause | Next step |
|---|---|---|
| Very high `calls`, tiny `mean_ms` | Chatty application, N+1 queries | Reduce call count, batch, cache |
| Few `calls`, large `mean_ms` | Poor plan, missing index | Run `EXPLAIN (ANALYZE, BUFFERS)` |
| Large `rows / calls` | Over-fetching | Add filters or pagination |
| Large `shared_blks_read` | I/O-bound access | Check indexes and cache fit |
| Non-zero `temp_blks_written` | Spills to disk | Check `work_mem` and query shape |
The later chapters cover the last three rows in detail. For now, pick the top one to three rows and carry their queryid forward.
Verify the fix
After you change something, the old totals still include the slow period. Compare in one of two ways:
- Reset with
SELECT pg_stat_statements_reset();, run a representative workload, and rank again. - Take a snapshot of the view into a table before the change and a second one after, then subtract
callsandtotal_exec_timeperqueryid.
The snapshot approach does not discard anything and works on shared systems where a reset would disturb other people's measurements:
CREATE TABLE pgss_snapshot AS
SELECT now() AS taken_at, userid, dbid, queryid, calls, total_exec_time
FROM pg_stat_statements;Later, join the current view to pgss_snapshot on userid, dbid, and queryid. The difference in total_exec_time is the time spent in that interval. Rows whose entries were evicted or reset in between need care, because their counters can go backwards.
Exercise
A server's top row by totalexectime is SELECT ... FROM sessions WHERE token = $1 with 52 million calls, a mean of 0.4 ms, and 38% of all recorded time. A second row, a monthly report, has 2 calls and a mean of 45 seconds, and 0.01% of the time. Which one do you investigate first, and what do you check?
Show answer
Start with the sessions lookup, because it holds 38% of the total time. Its mean is already small, so the likely gains are in reducing the call count (caching, avoiding repeated lookups per request) or confirming it uses an index with EXPLAIN (ANALYZE, BUFFERS) on a real token. The report is slow per call but costs almost nothing overall, so it only matters if users are waiting on it, and then you would rank by meanexectime instead.
Exercise
Why can summing totalexectime over every row of pgstatstatements give a number larger than the elapsed time, and when does it also double count?
Show answer
The column adds the execution time of all sessions, so concurrent queries add up faster than the clock runs. It also double counts when pgstatstatements.track is set to all, because a function call's time already contains the time of the statements inside it, and those inner statements have their own rows.