Sub topic 11
Unstable queries: stddev, min, and max
This chapter assumes you can read the core pg_stat_statements columns (calls, total_exec_time, mean_exec_time), that the extension is already enabled, and that you know what a query plan is. It uses the column names from PostgreSQL 13 and later.
Why a mean can hide a problem
mean_exec_time is one number per query. Two queries can share a mean of 20 ms and behave very differently:
- Query A takes 18 to 22 ms on every call.
- Query B takes 1 ms on 95% of calls and 381 ms on the other 5%.
Users rarely notice query A. Query B causes timeouts, stalled requests, and complaints that the application is "sometimes slow". Ranking by mean or total time cannot tell the two apart. Three more columns can.
| Column | Meaning |
|---|---|
| `min_exec_time` | Fastest single execution since statistics were last reset, in milliseconds |
| `max_exec_time` | Slowest single execution since the last reset, in milliseconds |
| `stddev_exec_time` | Population standard deviation of execution time, in milliseconds |
Standard deviation measures how far executions typically fall from the mean. A value near zero means the query runs consistently. A value several times larger than the mean means a long tail of slow runs.
Measuring instability with a ratio
An absolute stddev of 50 ms means something different for a query whose mean is 500 ms than for one whose mean is 2 ms. Dividing stddev by the mean gives the coefficient of variation (CV). It is a unitless measure of relative spread:
- CV below 0.3 usually means a steady query.
- CV around 1 means the typical deviation is as large as the mean itself.
- CV above 2 means a heavy tail, with a few executions far slower than the rest.
These thresholds are rules of thumb, not PostgreSQL settings. This query lists the least stable queries that have enough calls to be meaningful:
SELECT queryid,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(stddev_exec_time::numeric, 2) AS stddev_ms,
round((stddev_exec_time / nullif(mean_exec_time, 0))::numeric, 2) AS cv,
round(min_exec_time::numeric, 2) AS min_ms,
round(max_exec_time::numeric, 2) AS max_ms,
left(query, 60) AS query
FROM pg_stat_statements
WHERE calls >= 100
ORDER BY stddev_exec_time DESC
LIMIT 10;The calls >= 100 filter matters. With one call, stddev is 0 and min equals max. With a handful of calls, the figures are too noisy to act on. nullif avoids a division by zero for statements whose mean rounds to zero.
Sort by stddev_exec_time to find where the absolute spread is largest. Sort by cv to find the least predictable queries regardless of size. For tuning, the first list is usually more useful, because a wide spread on an already fast query rarely matters.
A worked example
This example builds a table with skewed data. Customer 1 owns most of the rows, and every other customer owns very few.
CREATE TABLE ticket (
id bigserial PRIMARY KEY,
customer_id int NOT NULL,
note text NOT NULL
);
INSERT INTO ticket (customer_id, note)
SELECT CASE WHEN g <= 500000 THEN 1 ELSE 2 + g % 5000 END,
'x'
FROM generate_series(1, 600000) AS g;
CREATE INDEX ON ticket (customer_id);
ANALYZE ticket;
SELECT pg_stat_statements_reset();Now run the same query shape with different values. Repeat the pair several times in psql:
SELECT count(note) FROM ticket WHERE customer_id = 1;
SELECT count(note) FROM ticket WHERE customer_id = 42;Normalization turns both statements into WHERE customer_id = $1, so they share one queryid and one row in the view. Look at that row:
SELECT calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(stddev_exec_time::numeric, 2) AS stddev_ms,
round(min_exec_time::numeric, 2) AS min_ms,
round(max_exec_time::numeric, 2) AS max_ms,
query
FROM pg_stat_statements
WHERE query LIKE '%FROM ticket%';The row for customer 42 pulls min_ms down to a fraction of a millisecond, because a few index lookups are cheap. The row for customer 1 pushes max_ms up by orders of magnitude, because it must count 500,000 rows. The stddev is large relative to the mean. No single parameter value is "the" cost of this query, which is why the view shows a wide spread.
Common causes of instability
A wide spread tells you that executions differ. It does not tell you why. These are the usual reasons:
| Cause | Typical clue in the statistics | What to check next |
|---|---|---|
| Skewed data and parameter values | Fast `min`, slow `max`, similar `rows` per call varies widely | Run `EXPLAIN (ANALYZE, BUFFERS)` with a common and a rare value |
| Plan changes between calls, including generic and custom plans in prepared statements | Spread appears only for prepared or parameterized clients | Compare plans for the same query with different parameters |
| Cold versus warm cache | High `shared_blks_read` relative to `shared_blks_hit` | Check hit percentage, then run the query twice |
| Lock waits | Large `max` with little buffer or row activity | Check `pg_locks` and `log_lock_waits` |
| Temporary file spills on some runs | `temp_blks_written` above zero | Look at `work_mem` and the query shape |
| Competing load, checkpoints, or autovacuum | Many unrelated queries show spikes at the same time | Compare with system metrics for the same period |
Execution time includes time spent waiting for locks and, indirectly, time lost to I/O or CPU contention. A query can be slow because of what else the server was doing, not because of anything in its own plan.
Limits of these three columns
Three gotchas apply to everything above.
First, the numbers are cumulative since the last reset, not a recent window. A max_exec_time of 30 seconds could come from one bad afternoon last month, and the query may be fine today. The view has no timestamps for individual executions.
Second, there is no distribution. You get a mean, a spread, and two extremes. You cannot tell whether the slow runs are 5% of calls or one call out of a million. A high max with a low stddev suggests a single outlier. A high stddev with a high max suggests a pattern. For real percentiles you need logs or an external monitoring system.
Third, stddev_exec_time is sensitive to a few large values. Because the standard deviation squares each difference from the mean, one very slow call can dominate it, especially when calls is small. Treat results with fewer than a few hundred calls as hints.
Narrowing the time window for min and max
Because min and max are lifetime values, an old outlier can hide current behavior. On PostgreSQL 17 and later, you can reset only the min and max values for all statements and leave calls, total time, and the other counters in place:
SELECT pg_stat_statements_reset(0, 0, 0, true);The arguments are userid, dbid, queryid, and minmax_only. A 0 in the first three positions means "all". The minmax_stats_since column of the view records when min and max were last reset. On older versions, only a full pg_stat_statements_reset() is available, and it discards every counter.
Take a snapshot of the view into a table before a full reset if you want to compare periods later:
CREATE TABLE pgss_snapshot AS
SELECT now() AS taken_at, *
FROM pg_stat_statements;From a flagged query to evidence
The statistics only nominate suspects. The usual workflow has four steps:
- Rank by stddev or CV with a sensible
callsthreshold. - Read the query text and think about which parameter values might behave differently.
- Check the buffer and temp columns for the same row to see whether I/O or spills line up with the spread.
- Reproduce both ends of the range with
EXPLAIN (ANALYZE, BUFFERS), using a typical value and a worst-case value.
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(note) FROM ticket WHERE customer_id = 1;
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(note) FROM ticket WHERE customer_id = 42;If the two plans differ, such as a sequential scan against an index scan, you have found the cause of the spread. The fix may be different indexes, better statistics, or changing the application so the heavy case takes a different path.
Exercise
A query has calls = 20000, meanexectime = 4 ms, stddevexectime = 18 ms, minexectime = 0.3 ms, and maxexectime = 2400 ms. What does this suggest, and what do you do next?
Show answer
The stddev is far above the mean (CV of 4.5) and max is about 600 times the mean, so most calls are fast and a minority are very slow. First find out why those calls differ: check skewed parameter values, lock waits, and cold-cache reads (compare sharedblksread to sharedblkshit). Then reproduce the fast and slow cases with EXPLAIN (ANALYZE, BUFFERS). Because min and max are lifetime values, also confirm the slow case still happens by resetting min and max (PostgreSQL 17 and later) or the full statistics, and watching again.
Exercise
Why does a statement with calls = 1 show stddevexectime = 0, and why should you filter on calls before sorting by stddev?
Show answer
With one execution there is nothing to deviate from, so the spread is 0 and min equals max. With very few calls the figures are noisy, and a single slow call can dominate the standard deviation. Filtering on a minimum number of calls, such as calls >= 100, keeps the ranking focused on queries with enough history to be meaningful.