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.
| Column | Meaning | Typical use |
|---|---|---|
| calls | Number of executions | Find high-frequency statements |
| total_exec_time | Cumulative execution time in milliseconds | Rank queries by overall server load |
| mean_exec_time | Average time per execution | Spot individually slow statements |
| stddev_exec_time | Spread of execution times | Detect unstable plans or data skew |
| rows | Total rows retrieved or affected | Find queries returning excessive data |
| shared_blks_hit / read | Buffer cache hits and disk reads | Measure cache efficiency per query |
| temp_blks_written | Blocks spilled to temporary files | Identify undersized work_mem for sorts and hashes |
| total_plan_time | Cumulative planning time | Find statements with expensive planning |
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.
| Tool | Granularity | Main strength | Main gap |
|---|---|---|---|
| pg_stat_statements | Aggregated per query shape | Low-overhead workload ranking | No parameters or plans |
| Slow query log | Individual executions over a threshold | Exact text and parameters | Misses fast, frequent queries |
| EXPLAIN ANALYZE | One execution on demand | Full execution plan with timings | Manual and not continuous |
| auto_explain | Plans of slow executions | Captures plans automatically | Higher overhead with timing enabled |
| pg_stat_activity | Current sessions | Live waits and blocking | No history after completion |
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.
| Parameter | Default | Effect |
|---|---|---|
| pg_stat_statements.max | 5000 | Maximum number of tracked entries |
| pg_stat_statements.track | top | Track top-level statements, all including nested, or none |
| pg_stat_statements.track_utility | on | Include utility commands such as VACUUM or COPY |
| pg_stat_statements.track_planning | off | Collect planning time and counts |
| pg_stat_statements.save | on | Persist statistics across clean server restarts |
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.
| Symptom | Cause | Remedy |
|---|---|---|
| Good mean time hides slow outliers | Averages mask skewed parameters | Check stddev and max_exec_time, then sample with auto_explain |
| Same query appears many times | Different IN-list lengths or dynamic SQL | Use arrays with ANY or upgrade to a version that merges list constants |
| Top query list changes after restart | Statistics were reset or not saved | Snapshot the view regularly into a history table |
| Query text shows placeholders only | Normalization removes literals | Reproduce with real values from logs or the application |
| Many entries are evicted | pg_stat_statements.max set too low | Raise the limit and reduce distinct query shapes |
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.