Sub topic 6
Slow per call versus expensive in aggregate
This chapter assumes you have already enabled pg_stat_statements, can run queries in psql, and know what calls, total_exec_time, and mean_exec_time mean. The column names used here apply to PostgreSQL 13 and later.
Two different questions
A query can cost you time in two ways. It can be slow every time it runs, or it can be fast but run so often that the small costs add up. The same view answers both questions, but you have to sort it differently.
The relationship is simple:
total_exec_time = calls × mean_exec_timeThis identity is why a single ranking is not enough. Sorting by total_exec_time surfaces the queries that use the most database time overall. Sorting by mean_exec_time surfaces the queries that are slowest on each run. A query can rank high on one list and absent from the other.
| Query pattern | calls | mean_exec_time | total_exec_time | Typical cause |
|---|---|---|---|---|
| Heavy hitter | 2,000,000 | 0.8 ms | about 26 min | Small lookup repeated by application code |
| Slow outlier | 40 | 9,000 ms | 6 min | Report or batch job with a poor plan |
| Both | 50,000 | 120 ms | 100 min | Missing index on a hot path |
| Neither | 200 | 2 ms | under 1 s | Not worth attention |
Which one to fix first depends on what hurts. If users complain about one page that loads slowly, start with mean time. If the server's CPU or I/O is saturated and everything feels sluggish, start with total time.
Finding queries that are slow per call
To find queries that are slow on each run, order by mean_exec_time. Add a minimum calls filter so that one-off statements do not fill the list.
SELECT queryid,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(max_exec_time::numeric, 2) AS max_ms,
left(query, 80) AS query
FROM pg_stat_statements
WHERE calls >= 50
ORDER BY mean_exec_time DESC
LIMIT 10;The calls >= 50 threshold is a judgment call. Without it, a single ad hoc CREATE INDEX or a manual SELECT you ran an hour ago can top the list. A mean based on one execution says nothing about typical behavior.
Choose the threshold from your workload. On a system where batch jobs run a few times a day, a threshold of 50 hides them. Lower it, or run the query a second time with calls >= 1 and read the results by eye.
Also read max_exec_time next to the mean. If the max is far above the mean, a few bad runs may be pulling the average up. That points to instability rather than a uniformly slow query, which a later chapter covers.
Finding queries that are expensive in aggregate
To find queries that cost the most overall, order by total_exec_time. It is often useful to add the share of all recorded time that each query accounts for.
SELECT queryid,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
round((100 * total_exec_time
/ sum(total_exec_time) OVER ())::numeric, 1) AS pct_of_total,
left(query, 60) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;The window expression sum(total_exec_time) OVER () adds up the time across every row in the view, not only the ten you display. The result, pct_of_total, tells you how much of the measured workload each query represents. If the top query accounts for 40 percent, one fix may change the whole server. If the top ten each account for 3 percent, no single fix will, and you may need to look at the application's access pattern instead.
A heavy hitter often looks harmless in isolation. A query that takes 0.5 ms looks fine in EXPLAIN. Yet if the application runs it 10 million times an hour, it consumes more than an hour of database time. The fix is frequently not a faster query but fewer calls, for example by batching lookups or removing a query repeated inside a loop (the "N+1" pattern).
Combining both views in one query
You can flag both kinds of candidate in a single result by computing a rank for each measure.
WITH ranked AS (
SELECT queryid,
calls,
total_exec_time,
mean_exec_time,
rank() OVER (ORDER BY total_exec_time DESC) AS rank_total,
rank() OVER (ORDER BY mean_exec_time DESC)
FILTER (WHERE calls >= 50) AS rank_mean,
query
FROM pg_stat_statements
)
SELECT queryid, calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 1) AS mean_ms,
rank_total, rank_mean,
left(query, 60) AS query
FROM ranked
WHERE rank_total <= 10 OR rank_mean <= 10
ORDER BY rank_total;Note that FILTER on a window function is not allowed for ranking functions such as rank(). The query above will therefore fail with an error. Use a conditional ordering inside a subquery instead:
WITH base AS (
SELECT queryid, calls, total_exec_time, mean_exec_time, query
FROM pg_stat_statements
),
by_total AS (
SELECT queryid,
rank() OVER (ORDER BY total_exec_time DESC) AS rank_total
FROM base
),
by_mean AS (
SELECT queryid,
rank() OVER (ORDER BY mean_exec_time DESC) AS rank_mean
FROM base
WHERE calls >= 50
)
SELECT b.queryid, b.calls,
round(b.total_exec_time::numeric, 1) AS total_ms,
round(b.mean_exec_time::numeric, 1) AS mean_ms,
t.rank_total, m.rank_mean,
left(b.query, 60) AS query
FROM base b
JOIN by_total t USING (queryid)
LEFT JOIN by_mean m USING (queryid)
WHERE t.rank_total <= 10 OR m.rank_mean <= 10
ORDER BY t.rank_total;A query with both ranks small is the strongest candidate: it is slow and frequent.
Reading the numbers with care
Several details affect how you should interpret these rankings.
- Mean hides the shape. A mean of 100 ms may mean every run takes about 100 ms, or that most runs take 5 ms and a few take 5 seconds. Check
stddev_exec_time,min_exec_time, andmax_exec_timebefore deciding what the problem is. - Total time includes waiting. Execution time includes time spent waiting on locks and I/O during execution. A query with a large total may be slow because of contention, and no change to the query alone will help.
- Planning time is separate.
total_exec_timeexcludes planning. Whenpg_stat_statements.track_planningis on, planning cost appears intotal_plan_timeandmean_plan_time. It is off by default because it adds overhead. If you suspect very short queries with expensive planning, enable it and compare the two. - The window matters. Counters accumulate from the last reset or server start. A query that was heavy last month and has since been fixed can still lead the list. Reset the statistics, as the reset chapter describes, to measure a defined period.
- Different parameters, same row. Normalization merges executions with different constants. A query that is fast for one customer and slow for another appears as a single row, and the mean blends them.
A short workflow
- Rank by
total_exec_timeand note the top few queries and theirpct_of_total. - Rank by
mean_exec_timewith acallsfilter and note the slowest ones. - Mark queries that appear on both lists.
- For each candidate, decide whether the problem is frequency (reduce calls, cache, batch) or per-call cost (index, rewrite, fix the plan).
- Take per-call candidates to
EXPLAIN (ANALYZE, BUFFERS)with real parameter values.
Exercise
A query shows calls = 3,000,000, meanexectime = 0.4 ms, and totalexectime of about 20 minutes. Another shows calls = 30, meanexectime = 4,000 ms, and totalexectime of 2 minutes. Which one ranks first when ordering by totalexectime and which one ranks first when ordering by meanexectime (with calls >= 10)? Which kind of fix is each most likely to need?
Show answer
The first query ranks first by totalexectime (20 minutes versus 2 minutes). The second ranks first by meanexectime (4,000 ms versus 0.4 ms). The first is a heavy hitter, so the likely fix is to reduce how often it runs, for example by batching or caching, since 0.4 ms per call is already fast. The second is slow per call, so the likely fix is to examine its plan with EXPLAIN (ANALYZE, BUFFERS) and add an index or rewrite it.
Exercise
Why does the first combined ranking query in this chapter fail, and what is the simplest way to compute a mean-time rank that ignores queries with few calls?
Show answer
PostgreSQL does not allow FILTER on a window function such as rank(), because FILTER applies only to aggregate functions. Compute the rank in a separate subquery or CTE that already applies WHERE calls >= 50, then join it to the total-time ranking.