skip to content

In PostgreSQL, how do you use pg_stat_statements to find the query costing the most total time, and why not rank by mean_exec_time?

level: middleimportance: must knowfreq 72%

answer

  1. calls times mean
  2. one row per normalised query
  3. total_exec_time, in milliseconds
  4. reset or diff two snapshots

basics

~20 s

Query pg_stat_statements ordered by total_exec_time, which is calls times mean time per normalised query. A 3 ms query run two million times outweighs one 45-second report, so ranking by mean finds slow queries rather than expensive ones.

solid answer

~40 s

`pg_stat_statements` keeps one row per normalised query: the same statement with different constants shares a `queryid`, and the text shows `$1`, `$2`. I order it by `total_exec_time` (milliseconds) and show each row's share of the sum, together with `calls`, `mean_exec_time`, `rows` and `shared_blks_hit + shared_blks_read`. Total is what consumes CPU, I/O and connection time. On a travel-booking backend, a 3 ms seat-availability lookup called two million times a day costs 6,000 s, while a 45 s nightly report costs 45 s. Ranking by mean would put the report first and send me to optimise the wrong thing. The counters are cumulative, so I measure a window, either by calling `pg_stat_statements_reset()` or by diffing two snapshots, and I check `pg_stat_statements_info.dealloc` for evicted entries.

code

sql · 9 lines
sql
SELECT queryid,
       calls,
       round(total_exec_time::numeric, 0) 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,
       left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

go deeper

for a junior

Remember that pg_stat_statements groups queries that differ only in constants into one row, and that total_exec_time is the column for what costs the most overall.

for a middle

Explain total as calls times mean with a concrete example, and read buffers, rows and temp blocks per call to say why a top query is expensive.

for a senior

Measure a window with a reset or snapshot diffs, watch dealloc for eviction churn, and know which columns 17 renamed and what 18's IN-list squashing does to entry counts.

for a principal

Decide what to optimise from the share of server time, weighing one endpoint's latency target against fleet-wide cost, and make the snapshot history a standing monitoring feed.

## What pg_stat_statements records `pg_stat_statements` is a contrib extension that tracks planning and execution statistics for every statement the server runs. It keeps **one row per distinct combination** of database, user, query ID and top-level flag (`dbid`, `userid`, `queryid`, `toplevel`). The **query ID** is a hash of the statement after parse analysis. Statements that differ only in literal constants hash the same, so they share a row, and the stored text shows the constants as `$1`, `$2` and so on. This is **normalisation**, and it is what makes the totals meaningful. Each row accumulates counters from the moment it is created (`stats_since`): - `calls` and `rows` - `total_exec_time`, `mean_exec_time`, `min_exec_time`, `max_exec_time` and `stddev_exec_time`, all in **milliseconds** - `shared_blks_hit` and `shared_blks_read`: shared-buffer pages found in cache or read in - `temp_blks_written`: work that spilled to temporary files - `wal_records` and `wal_bytes`, plus `wal_buffers_full` in 18 - `total_plan_time` and its siblings, filled only when `pg_stat_statements.track_planning` is on (default `off`) The module needs its library preloaded and a server restart (that belongs to the extensions topic). You also run `CREATE EXTENSION pg_stat_statements` in the database you query from. Once loaded, it tracks statements in all databases. Seeing other users' query text and `queryid` needs superuser or the `pg_read_all_stats` role. ## Total, not mean Take a travel-booking backend over one day: | normalised query | calls | mean | total | |---|---|---|---| | seat availability for a flight | 2,000,000 | 3 ms | 6,000 s | | fare search with filters | 40,000 | 90 ms | 3,600 s | | nightly revenue report | 1 | 45 s | 45 s | Ranked by `mean_exec_time`, the report comes first. It is slow, but it costs 45 seconds a day. `total_exec_time` is calls multiplied by mean, so it measures each query's **share of the server's working time**, and that share drives CPU, buffer reads and how long connections stay busy. Shaving 10% off the seat lookup saves 600 s a day. Making the report instant saves 45 s. Mean and max still matter when the question is one endpoint's latency target, but the costliest query is the one with the largest total. ```sql SELECT queryid, calls, round(total_exec_time::numeric, 0) 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, rows / NULLIF(calls, 0) AS rows_per_call, (shared_blks_hit + shared_blks_read) / NULLIF(calls, 0) AS blks_per_call, left(query, 80) AS query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10; ``` ## Reading the top rows 1. **Share of the total.** If the top three entries account for 60% of execution time, that is where the work goes. 2. **Pages per call.** A lookup that touches thousands of buffers to return one row is reading far more than it needs. Fixing it is indexing work, but this column is how you spot it. 3. **Rows per call.** A query returning 5,000 rows to a page that shows 20 is an application problem, not a database one. 4. **`temp_blks_written` above zero.** Sorts or hashes are spilling to disk. 5. **`stddev_exec_time` large next to the mean.** Some executions are far slower than others. Pair this with `auto_explain` to catch a slow instance's plan. The I/O timing columns (`shared_blk_read_time`, `shared_blk_write_time`) stay at zero unless `track_io_timing` is on. It is off by default. ## Measuring a window, not all history The counters run from when each entry was created, or from the last reset. To see a specific period: - call `pg_stat_statements_reset()`, which returns the reset time and can target one `userid`, `dbid` or `queryid`, or with `minmax_only => true` reset only the min/max columns; or - snapshot the view twice into a table and subtract, joining on `userid`, `dbid`, `queryid` and `toplevel`. Check `pg_stat_statements_info.dealloc` as well. When more distinct statements appear than `pg_stat_statements.max` (default 5000, changeable only at server start), the least-executed entries are evicted. Steady churn means the totals are incomplete. The usual cause is SQL that does not normalise, such as identifiers built into the text. ## What 17 and 18 changed - **18:** query-ID computation squashes a list of constants, so `IN (1, 2, 3)` and `IN (1, ..., 8)` share one entry, shown as `$1 /*, ... */`. `CREATE TABLE AS` and `DECLARE` are tracked, `SET` values are parameterised, and `parallel_workers_to_launch`, `parallel_workers_launched` and `wal_buffers_full` were added. Query IDs now group queries by relation name, so the same query against same-named tables in different schemas shares an entry. - **17:** `blk_read_time` and `blk_write_time` became `shared_blk_read_time` and `shared_blk_write_time`, with `local_` counterparts. `stats_since`, `minmax_stats_since` and the `minmax_only` reset argument were added. Monitoring queries written for 16 that select `blk_read_time` fail on 17 and 18.

  • The top entry's query text shows literal values instead of $1 placeholders. What does that tell you?
    Normalisation probably did not apply. Either entries are being evicted and recreated quickly (look at `pg_stat_statements_info.dealloc` against `pg_stat_statements.max`), or the statement really differs each time, for example identifiers or table names built into the SQL. Either way, the totals for that query family are split or incomplete.
  • Why is total_plan_time zero for every row while total_exec_time is populated?
    Planning time is tracked only when `pg_stat_statements.track_planning` is on, and it is off by default because of the contention it adds on hot entries. `total_exec_time` covers execution only, so a query that is expensive to plan stays invisible until you enable it.
  • How do you rank only the last hour, not the totals since the server started?
    Snapshot `pg_stat_statements` into a table, wait an hour, snapshot again, and subtract per `userid, dbid, queryid, toplevel`. Alternatively, call `pg_stat_statements_reset()` at the start of the window and accept that it clears everyone's history.

  • Order pg_stat_statements by mean_exec_time to find the most expensive query.
  • pg_stat_statements stores one row per distinct query text, constants included.
  • total_exec_time already includes planning time for every statement.
  • pg_stat_statements works after CREATE EXTENSION alone, with no preload or restart.
  • blk_read_time is still the column for read I/O time in PostgreSQL 18.

Assumes PostgreSQL 18: constant IN-lists collapse to one entry since 18, and 17 renamed blk_read_time/blk_write_time to shared_blk_read_time/shared_blk_write_time.