Sub topic 9
Resetting Statistics and Measuring a Time Window
The counters in pg_stat_statements are cumulative. They start at zero when the extension is first loaded or last reset, and they only grow. A ranking by total_exec_time therefore covers everything since that starting point, which might be six months of workload or ten minutes. This chapter covers two ways to measure a specific window: resetting the counters, and taking snapshots to compute differences.
This chapter assumes you have already enabled the extension, you can read the core columns (calls, total_exec_time, rows), and you know how queryid groups statements. A superuser, or a role with the right privileges, is needed for the reset steps.
Why a window matters
Cumulative totals blur several different periods together:
- A nightly batch job from last month can still sit at the top of
total_exec_timeeven though it was fixed. - A query introduced by yesterday's deploy has had little time to accumulate, so it ranks below older queries even if it is far more expensive per hour.
- Averages such as
mean_exec_timecan hide a recent regression. If a query ran fast for 10 million calls and slowly for the last 10,000, the mean barely moves.
To answer "what is slow right now?" or "what did the load test cost?", you need statistics for a bounded period. There are two ways to get them: reset and wait, or snapshot and subtract.
Approach 1: reset, run, read
pg_stat_statements_reset() discards the accumulated statistics. You then run the workload you care about and query the view.
SELECT pg_stat_statements_reset();
-- run the workload you want to measure, then query pg_stat_statements againAfter the reset, the view is empty and fills again as statements execute. Every number you read afterwards describes only the period since the reset.
The function accepts optional arguments to reset less than everything:
-- PostgreSQL 12 and later: reset one user, one database, or one query
-- Arguments are userid, dbid, queryid. A value of 0 means "all".
SELECT pg_stat_statements_reset(0, 0, 1234567890123456789);Replace the example queryid with a value taken from your own view. Resetting a single entry is useful after you ship a fix for one query. You get a clean measurement of the new behavior without losing everything else.
Resetting only min and max
min_exec_time and max_exec_time are remembered for the life of the entry. One slow run last month leaves a large max_exec_time indefinitely, even if the query has behaved since. PostgreSQL 17 added a fourth argument, minmax_only, that clears only these values and keeps the cumulative counters.
-- PostgreSQL 17 and later: reset only min/max timing for all entries
SELECT pg_stat_statements_reset(0, 0, 0, true);On older versions, the only way to clear max_exec_time is a full or per-entry reset.
Checking when the statistics started
Before you trust a ranking, confirm how long it has been accumulating. From PostgreSQL 14, the helper view pg_stat_statements_info records the last reset time.
SELECT dealloc, stats_reset
FROM pg_stat_statements_info;stats_reset is the moment the statistics began. dealloc counts how many times entries were evicted because the table was full, which matters for the limits covered later in this tutorial. PostgreSQL 17 also adds stats_since and minmax_stats_since columns to pg_stat_statements itself, so each row shows when its own counters began.
Approach 2: snapshot and subtract
Snapshots avoid destroying anything. You copy the view into an ordinary table at the start of the window, then compare the live view against that copy later. The difference is the activity inside the window.
First capture the baseline.
CREATE TABLE pgss_snapshot AS
SELECT now() AS captured_at,
userid,
dbid,
toplevel,
queryid,
calls,
total_exec_time,
rows,
shared_blks_read,
temp_blks_written
FROM pg_stat_statements;The toplevel column exists from PostgreSQL 14. On version 13 or earlier, remove it here and from the join below.
When the window has passed, compute the delta.
SELECT cur.queryid,
cur.calls - coalesce(snap.calls, 0) AS calls_delta,
round((cur.total_exec_time - coalesce(snap.total_exec_time, 0))::numeric, 2)
AS total_ms_delta,
round(((cur.total_exec_time - coalesce(snap.total_exec_time, 0))
/ nullif(cur.calls - coalesce(snap.calls, 0), 0))::numeric, 2)
AS mean_ms_in_window,
cur.shared_blks_read - coalesce(snap.shared_blks_read, 0) AS blks_read_delta,
left(cur.query, 80) AS query
FROM pg_stat_statements AS cur
LEFT JOIN pgss_snapshot AS snap
USING (userid, dbid, toplevel, queryid)
WHERE cur.calls > coalesce(snap.calls, 0)
ORDER BY total_ms_delta DESC
LIMIT 10;Three details make this query behave correctly:
LEFT JOINwithcoalesce(..., 0)keeps statements that did not exist at snapshot time. These are often the new queries you most want to see.- The
WHEREclause drops statements that did not run in the window. It also drops rows where the current count is lower than the snapshot, which signals that the entry was evicted and recreated, or that a reset happened. mean_ms_in_windowdivides the time delta by the call delta. This is the real average for the window, not the lifetime average stored inmean_exec_time.
Repeat the snapshot step regularly, for example every five minutes from a scheduled job, and you have a crude history of workload over time. Give each capture its own captured_at value, and insert into one table instead of recreating it.
Choosing between the two approaches
| Question | Reset | Snapshot and subtract |
|---|---|---|
| Destroys existing statistics | Yes | No |
| Works if you lack reset privilege | No | Yes, with read access to the view |
| Needs extra storage | No | Yes, a small table |
| Resets `max_exec_time` | Yes | No (max is lifetime, not per window) |
| Safe on a shared system | Only with coordination | Yes |
| Risk of misreading after eviction | Low | Needs the `WHERE` guard above |
The max_exec_time row deserves attention. Subtraction works for counters that only add up: calls, total_exec_time, rows, and the block counts. It does not work for min_exec_time, max_exec_time, or stddev_exec_time, because those cannot be derived from two totals. For per-window extremes, you must reset (or on version 17, reset min/max only) and measure fresh.
A typical measurement workflow
A realistic example is a load test. You reset the statistics immediately before the test starts, run the test for 20 minutes, then rank by total_exec_time. Everything in the ranking was caused by the test. Without the reset, the same ranking would mix in unrelated production traffic from the previous weeks.
Common mistakes
- Measuring too short a window. If a query runs once an hour, a five-minute window may miss it entirely. Match the window to the workload's rhythm.
- Measuring too long after a reset. After a few hours, the cumulative view again blends different periods. Take a new snapshot or reset when the question changes.
- Forgetting the restart case. Statistics are saved to disk at clean shutdown and reloaded at startup when
pg_stat_statements.saveis on (the default). After a crash, they are lost. Astats_resetvalue that is newer than expected can mean a crash or an unexpected reset. - Comparing windows of different lengths by total time. A 10-minute window and a 60-minute window cannot be compared by
total_ms_delta. Divide by the window length, or compare means and per-minute call rates. - Ignoring permissions. By default, only superusers can execute the reset function. Other roles need an explicit grant, for example
GRANT EXECUTE ON FUNCTION pg_stat_statements_reset(oid, oid, bigint) TO monitoring_role;. On version 17 the signature has an extra boolean argument, so check it with\df pg_stat_statements_resetin psql.
Exercise
You reset pgstatstatements at 09:00 and run a ranking query at 09:30. One query shows calls = 12 and maxexectime = 4,800 ms. A teammate says the max must come from the last 30 minutes. Is that right? How would you check, and what would you do to measure the max for a later window?
Show answer
Yes, on a system where nobody else reset the statistics. The reset at 09:00 cleared maxexectime, so any value at 09:30 comes from executions after 09:00. Confirm this by checking statsreset in pgstatstatementsinfo (PostgreSQL 14 and later), which should read 09:00 rather than a later time if someone else reset in between. To measure maxexectime for a later window, snapshot subtraction cannot help because max is not additive. Reset again at the start of the new window (or on PostgreSQL 17, call pgstatstatements_reset(0, 0, 0, true) to clear only min and max) and read the view at the end.
Exercise
A snapshot-delta query shows a negative calls_delta for one query. What are two possible causes, and how does the WHERE clause in this chapter handle them?
Show answer
Either the statistics were reset between the snapshot and the current read, or the entry was evicted when the table reached pgstatstatements.max and was later recreated from zero. In both cases the current calls value is lower than the snapshot value. The condition WHERE cur.calls > coalesce(snap.calls, 0) filters these rows out, so they do not appear as negative or misleading deltas. You can then check dealloc and statsreset in pgstatstatementsinfo to see which cause applied.