Skip to main content
pg_stat_statements: Postgres Query Analysis Without Guessing

pg_stat_statements: Postgres Query Analysis Without Guessing

KU
· Founder & Chief Editor
• 8 min read•Updated •

The single most useful Postgres extension you might not be using. The queries it surfaces, the indexes it implies, and the operational discipline of reading it weekly.

Key takeaways

  • Find slow Postgres queries by enabling pg_stat_statements and sorting by total_exec_time, not mean time.
  • Total time exposes fast queries run millions of times, which the slow query log never sees.
  • Loading the extension needs shared_preload_libraries and a restart; reset the counters at the start of an incident.

To find what is actually slowing Postgres down, load pg_stat_statements, then sort its view by total_exec_time, not mean_exec_time. It aggregates every query by shape, so it catches what the slow query log can't: a fast query run millions of times. Enabling it takes one restart; reading it weekly catches regressions before they become incidents.

Verified against

PostgreSQL 18 (18.6 docs), pg_stat_statements module, against the postgresql.org pg_stat_statements and error-reporting-and-logging docs. Checked October 2026.

The usual approach to Postgres performance is reactive: notice slow queries when users complain, EXPLAIN ANALYZE them, add indexes, repeat. pg_stat_statements turns that around, because you sort by what costs you instead of by what someone complained about.

What it actually does

pg_stat_statements normalizes every query (literals become placeholders like $1) and aggregates per normalized query: total execution time, calls, mean and max time per call, rows returned, shared blocks hit versus read, and I/O timing if enabled. The output reads "this query ran 1.2M times, took 4 hours in total, averages 12ms," which is a finding rather than a list of slow statements.

Enabling it

It ships with Postgres as a contrib module but isn't loaded by default. The docs are explicit that it needs extra shared memory, so it must go in shared_preload_libraries, and adding or removing it means a server restart. Plan for that.

postgresql.conf
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all
compute_query_id = on            # the query ID the module groups by
pg_stat_statements.max = 10000   # default is 5000 normalized queries
track_io_timing = on             # adds I/O timing data (small overhead)
SQL
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

track decides what gets recorded. top (the default) records only top-level statements, so queries issued inside functions vanish into the function call. If much of your logic lives in PL/pgSQL, use all, accepting a little more overhead and a fuller table. On most managed Postgres services the extension is available, and you set shared_preload_libraries through the provider's parameter settings rather than editing the file.

Sort by total time, because that is what burns CPU

The classic failure: CPU on the primary is pinned every afternoon, the slow query log is quiet because nothing crosses a 500ms log_min_duration_statement threshold, and the cause is a fast query run tens of thousands of times a minute. Sorting by mean_exec_time finds an analytics query that runs nine seconds once a day. Sort by total_exec_time instead:

SQL
SELECT
    substring(query for 100) AS query,
    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, 2) AS percent_total
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

Read percent_total first. It tells you whether the top 20 are 20% or 95% of the workload. The typical top line is something like SELECT * FROM sessions WHERE token = $1: a fraction of a millisecond per call, tens of millions of calls, a double-digit share of all database time. If it is already an index-only scan, no index will help. The fix is in the app, for example caching session validation instead of hitting Postgres on every request.

The other queries we keep in a notes file

Slow per call. Slow and frequent are different problems: a 5-second query called 10 times is less urgent than a 50ms query called 1M times, but both matter.

SQL
SELECT substring(query for 100), calls,
    round(mean_exec_time::numeric, 2) AS mean_ms,
    round(max_exec_time::numeric, 2) AS max_ms
FROM pg_stat_statements
WHERE calls > 100            -- drop one-off migrations and DBA sessions
ORDER BY mean_exec_time DESC
LIMIT 20;

High I/O. Swap the columns for shared_blks_read, shared_blks_hit, and round(100.0 * shared_blks_hit / NULLIF(shared_blks_hit + shared_blks_read, 0), 1) AS cache_hit_pct, filter to shared_blks_read + shared_blks_hit > 10000, and order by shared_blks_read DESC. A low hit percentage with high reads means the query goes to disk: it scans more than it should, or your working set doesn't fit in RAM. A partial index (say on status = 'active') often fixes the first case.

Rows per call. rows / NULLIF(calls, 0) ordered descending. A query returning 50,000 rows per call is either a batch job (fine), a missing LIMIT (a bug), or iteration that should be pagination.

The patterns the data keeps showing

One missing index dominates. SELECT FROM orders WHERE user_id = $1 at a 45ms mean sounds fine until you multiply by millions of calls. An index on user_id frees that CPU for everything else.

A query runs far more often than it should. "Why does this run 500k times an hour?" is usually an ORM N+1 or a forgotten polling loop, as with the session check above. The fix is often in code, not the database.

A function in the WHERE clause. It's evaluated per row; if it's slow, everything is slow. Refactor or memoize.

Slow only sometimes. Mean 50ms, max 8 seconds: usually a plan that flips between an index scan and a seq scan depending on parameters. pg_stat_statements shows the pattern (stddev_exec_time next to the mean makes it obvious); reading the query plan shows the cause.

Reset before you investigate, review weekly after

Counters are cumulative since the last reset or restart. During an incident, three weeks of totals drown the signal from the last hour, so we reset at the start of every investigation:

SQL
SELECT pg_stat_statements_reset();
-- wait ~10 minutes inside the problem window, then rerun the total-time query

The same reset gives you a clean baseline after a major optimization. Reset is superuser-only by default, and on PostgreSQL 18 it accepts (userid, dbid, queryid, minmax_only), so you can clear one query, or only its min/max timings, without wiping everything. The stats_since column tells you how long each row has been accumulating.

Outside incidents, the discipline is a 15-minute weekly review of the top 20: note what moved in (new feature? regression?) and what moved out. Before a release with significant database changes, snapshot the view and compare afterwards. Real-time alerting on the view is mostly noise; it is built for periodic review. Don't try to act on the whole top 50 either: the top 5-10 dominate.

Costs and caveats

Overhead. It is workload dependent and the docs give no single number; the setting they explicitly warn about is pg_stat_statements.track_planning, which can cause a noticeable penalty when many connections run identical statements. Leave it off (the default) unless you need planning times, and benchmark on your own workload if every microsecond counts.

Memory. Normalized queries live in shared memory sized by pg_stat_statements.max, and the memory is reserved even with track = none. If the dealloc counter in pg_stat_statements_info keeps climbing, entries are being evicted; raise max.

Replicas track themselves. On a replica, the view shows that replica's own query traffic, not the primary's. If reads go to a replica pool, check each node; your slow read may live on one you weren't looking at. Our guide to routing reads to Postgres replicas covers where that traffic ends up.

No plans, no values. It knows queries, not their plans, and normalization discards the actual parameter values. Pair it with EXPLAIN ANALYZE and targeted statement logging. The plans themselves are only as good as the planner's statistics, which depend on autovacuum keeping up.

Questions people ask

Why doesn't the slow query log show what's eating my Postgres CPU?

log_min_duration_statement logs only individual executions above a threshold. A query that takes 0.13ms never crosses a 500ms threshold, even if it runs millions of times and owns a large share of database time. pg_stat_statements aggregates by query shape, so sorting by total_exec_time exposes that death-by-a-million-fast-queries pattern the log is blind to.

Should I sort pg_stat_statements by mean_exec_time or total_exec_time?

Start with total_exec_time, because it shows where the database actually spends its time. mean_exec_time surfaces individually slow queries, which matter for user-facing latency but are often rare. Run both, filter the mean-time view to calls > 100 to drop one-offs, and fix the top of the total-time list first.

Does enabling pg_stat_statements require a restart?

Yes. The module needs extra shared memory, so PostgreSQL only loads it from shared_preload_libraries at server start; adding or removing it means a restart. After the restart, run CREATE EXTENSION pg_stat_statements; in the database you query from. Changing pg_stat_statements.max also needs a restart, so set it generously the first time, around 10,000 for apps with many distinct statements.

The decision, concretely

  • CPU high but the slow query log is quiet? Reset the stats, wait ten minutes, sort by total_exec_time.
  • Top query fast per call but huge in total? Cut the call count (caching, N+1 fix) before touching indexes.
  • Low cache_hit_pct with high reads? Look for a missing or partial index, then check whether the working set fits in RAM.
  • Nothing on fire? Fifteen minutes a week on the top 20, plus a snapshot around risky deploys.

The call we'd make

Install pg_stat_statements on every Postgres instance you run, and always sort by total_exec_time first. It costs a restart and a modest, workload-dependent overhead, and it usually pays for itself in the first incident. Then make the weekly review a habit, alongside the rest of the operational basics like pooling connections with PgBouncer and watching replication lag. The caveat: it tells you which queries cost the most, not why, so budget time for the plan reading that follows.

Sources

React
Share this post
Cite this article
Plain text

Kiril Urbonas (2026). pg_stat_statements: Postgres Query Analysis Without Guessing. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/postgres-pg-stat-statements-query-analysis

Markdown

[pg_stat_statements: Postgres Query Analysis Without Guessing](https://www.devopsness.com/blog/postgres-pg-stat-statements-query-analysis) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)

KU

Kiril Urbonas

Founder & Chief Editor

612 articles
View all articles by Kiril Urbonas

You might have missed

Evergreen posts worth revisiting.