pg_stat_statements

On this page 7

pg_stat_statements is a PostgreSQL extension that records cumulative execution statistics for every normalized SQL statement the server runs, including call counts, total and mean execution time, rows returned and buffer activity. In the performance work of databases, it is the standard starting point for answering a simple but decisive question: which queries consume the most server time.

Unlike a slow query log, which captures individual executions above a threshold, pg_stat_statements aggregates all executions of the same query shape into one row. That design makes it cheap enough to run permanently in production and reveals a category of problem that per-query logging often misses: fast queries that run millions of times.

How pg_stat_statements groups and measures queries

The extension works by hooking into the query executor and attributing the cost of each finished statement to an entry in shared memory. It must be loaded at server start through the shared_preload_libraries setting, after which CREATE EXTENSION pg_stat_statements exposes the view of the same name in a database.

Grouping relies on query normalization. The parser replaces literal constants with placeholders such as $1, so WHERE id = 42 and WHERE id = 97 map to one entry. Each entry is identified by a queryid, a hash of the post-parse analysis tree, combined with the user ID, the database ID and a top-level flag. Because the hash reflects the parsed structure, two statements with identical text can receive different queryids when they reference different objects, for example after a table is dropped and recreated.

The number of tracked entries is capped by `pg_stat_statements.max`, which defaults to 5,000. When the cap is reached, the least-executed entries are evicted, and the pg_stat_statements_info view reports how often deallocation happened. Frequent eviction is a sign that the cap is too low or that the application generates too many distinct query shapes.

Key columns and what they reveal

The view exposes several dozen columns; a small subset answers most tuning questions. The table below lists the columns practitioners consult first and what each one indicates.

ColumnMeaningTypical use
callsNumber of executionsFind high-frequency statements
total_exec_timeCumulative execution time in millisecondsRank queries by overall server load
mean_exec_timeAverage time per executionSpot individually slow statements
stddev_exec_timeSpread of execution timesDetect unstable plans or data skew
rowsTotal rows retrieved or affectedFind queries returning excessive data
shared_blks_hit / readBuffer cache hits and disk readsMeasure cache efficiency per query
temp_blks_writtenBlocks spilled to temporary filesIdentify undersized work_mem for sorts and hashes
total_plan_timeCumulative planning timeFind statements with expensive planning
Core columns of the pg_stat_statements view

Column names changed in PostgreSQL 13, when total_time was split into total_exec_time and total_plan_time. Planning statistics are collected only when pg_stat_statements.track_planning is enabled, which is off by default because it adds measurable overhead on some workloads. Later releases added WAL usage columns and JIT timing, so monitoring queries should be written against the server version in use.

How it compares with other performance tools

pg_stat_statements answers where time goes across the workload, but it does not show why a specific statement is slow. It complements, rather than replaces, tools that capture individual executions and plans.

ToolGranularityMain strengthMain gap
pg_stat_statementsAggregated per query shapeLow-overhead workload rankingNo parameters or plans
Slow query logIndividual executions over a thresholdExact text and parametersMisses fast, frequent queries
EXPLAIN ANALYZEOne execution on demandFull execution plan with timingsManual and not continuous
auto_explainPlans of slow executionsCaptures plans automaticallyHigher overhead with timing enabled
pg_stat_activityCurrent sessionsLive waits and blockingNo history after completion
pg_stat_statements and related diagnostic sources

A practical workflow uses pg_stat_statements to pick the right target, then the execution plan from EXPLAIN ANALYZE to understand it, and finally the same view again to verify the improvement after an index, rewrite or configuration change.

Configuring and using the extension in production

Most managed PostgreSQL services preload the extension by default, while self-managed servers need a restart after changing shared_preload_libraries. The overhead is generally modest, often cited as a few percent at most, though it depends on statement rate and on whether planning tracking is enabled.

ParameterDefaultEffect
pg_stat_statements.max5000Maximum number of tracked entries
pg_stat_statements.tracktopTrack top-level statements, all including nested, or none
pg_stat_statements.track_utilityonInclude utility commands such as VACUUM or COPY
pg_stat_statements.track_planningoffCollect planning time and counts
pg_stat_statements.saveonPersist statistics across clean server restarts
Main configuration parameters

Because the counters are cumulative since the last reset, a raw ranking mixes old and new behavior. Experienced teams take periodic snapshots and compute deltas, or call pg_stat_statements_reset() at a known moment before a measurement window. Ranking by total_exec_time rather than mean time usually exposes the queries whose optimization saves the most capacity.

Setting track to all makes statements inside functions and procedures visible, which matters for applications that keep logic in PL/pgSQL. Without it, a single function call appears as one opaque top-level entry.

Limitations and common mistakes

The aggregated model creates blind spots that mislead inexperienced users. The following table pairs typical symptoms with their cause and a remedy.

SymptomCauseRemedy
Good mean time hides slow outliersAverages mask skewed parametersCheck stddev and max_exec_time, then sample with auto_explain
Same query appears many timesDifferent IN-list lengths or dynamic SQLUse arrays with ANY or upgrade to a version that merges list constants
Top query list changes after restartStatistics were reset or not savedSnapshot the view regularly into a history table
Query text shows placeholders onlyNormalization removes literalsReproduce with real values from logs or the application
Many entries are evictedpg_stat_statements.max set too lowRaise the limit and reduce distinct query shapes
Frequent pitfalls when reading the statistics

The view also exposes query text to any role that can read it. Only superusers and members of pg_read_all_stats see text from other users, a deliberate privacy safeguard because normalized text can still reveal schema details. Finally, timings measure server-side execution only: network latency, client processing and connection pooling delays are invisible to it.

Put simply

pg_stat_statements is like an itemized bill for a database server. Instead of listing every single request, it groups similar requests together and shows how often each kind was made and how much time it cost in total.

That summary makes it easy to see where the effort really goes. Often the biggest cost is not one dramatic slow request but a small, quick request repeated thousands of times. Fixing that one line on the bill can free more capacity than any other change.

In practice

An online retailer running PostgreSQL 16 notices that database CPU sits near 85 percent during evening peaks, although the slow query log shows almost nothing at its 500 millisecond threshold. The database engineer resets the statistics before peak hours and ranks the view by total_exec_time two hours later.

The top entry is a product price lookup with a mean time of only 1.8 milliseconds but 4.2 million calls, which adds up to more than two hours of execution time. Its shared_blks_read value shows that it scans a large index range for every call. The team adds a composite index matching the filter and sort columns and caches prices in the application for 30 seconds.

A second reset and measurement the next evening shows calls down to 300,000 and mean time at 0.3 milliseconds. Peak CPU drops to about 40 percent, and the team adds a nightly snapshot of the view so future regressions can be compared against a baseline.