Finding slow queries with pg_stat_statements before changing any setting
When a self-hosted PostgreSQL server slows down under load, the fastest-looking move is to change a setting: raise work_mem, add connections, or lower a timeout. Start by measuring instead. The pg_stat_statements extension ranks queries by their cumulative cost, so the fixes you make target the statements that consume the most server time in aggregate, not the ones someone happened to notice. A single query that runs in a few milliseconds but executes a million times per hour can matter more than one report that takes minutes once a day.
According to the PostgreSQL documentation, the extension records execution statistics per normalized statement, meaning statements that differ only in literal constant values are grouped under one entry with a query ID. For each entry it keeps counters such as the number of calls, total and mean execution time, rows returned, and shared buffer hits and reads. Recent PostgreSQL versions also track planning time separately, which helps you tell whether a slow statement spends its time in the planner or in execution. Teams need the extension before an incident, because statistics only accumulate from the moment it is loaded. It requires shared_preload_libraries to include pg_stat_statements and a server restart, so confirm the exact behavior for your PostgreSQL version in the PostgreSQL documentation before you schedule the change.
Owners of the database should decide who reads these statistics, how often they are reset, and where the top entries are recorded. Ask your team to confirm that the extension is enabled on every node you may promote, since a standby that was never configured will hold no history after failover. Record the top entries on a schedule, because a reset or restart clears them. The output is a tuning backlog: each entry names a query, its call count, its total time and its buffer activity. Take that list into the rest of the work, and change one setting at a time only after the matching query shows the cost it claims to cause.
Which pg_stat_statements settings and ranking views fit each goal
This table pairs each pg_stat_statements setting and ranking view with the question it answers, so you can choose what to enable and what to sort by. Read it as a starting point: confirm exact parameter names and defaults in the documentation for your installed PostgreSQL version before changing anything. The main takeaway is that total time finds load, mean time finds single slow statements, and planning tracking is worth enabling only when plan cost is a suspect.
| Goal or setting | What it does | When it fits | Trade-off or watch-out |
|---|---|---|---|
| shared_preload_libraries | Loads pg_stat_statements at server start so it collects statistics | Every production cluster you plan to tune | Requires a server restart after the change; confirm the library name for your version |
| pg_stat_statements.max | Sets how many distinct statements the view keeps | Applications with many generated or ORM-built statement shapes | Raising it uses more shared memory; watch for entries being evicted under churn |
| pg_stat_statements.track | Chooses which statements are tracked: top level, all, or none | Overall load ranking; use all when functions run SQL you need to see | Tracking all statements adds entries for nested calls and can crowd the view |
| pg_stat_statements.track_utility | Controls whether utility commands such as maintenance statements are tracked | Finding batch jobs, COPY or maintenance that consume time | Usually a secondary concern; most tuning starts with ordinary queries |
| pg_stat_statements.track_planning | Records planning time and planning counts per statement | Plan-heavy workloads where short queries spend much time in the planner | Adds per-statement overhead on every plan; enable for a diagnostic window, then compare |
| Ranking by total time | Sorts by the sum of execution time across all calls | Overall load: finding where the server spends its time | A cheap query run very often can outrank a single slow report |
| Ranking by mean time | Sorts by average time per call | One slow endpoint or a report that is slow each time it runs | Can surface rarely run statements that barely affect overall load |
| Ranking by calls and rows | Sorts by execution count or rows returned | Chatty applications, N+1 patterns and oversized result sets | High call counts are not a fault by themselves; check whether each call is necessary |
How to enable pg_stat_statements and confirm it collects data
This sequence turns a default PostgreSQL server into one that records per-statement timing and call counts, so the team can rank queries from real workload data before changing any settings.
Confirm the extension ships with your build
Before editing configuration, check that the pg_stat_statements module is installed on the server. Your package or container image normally includes it with the contrib modules, so list the available extensions in the target database and confirm pg_stat_statements appears. If it is missing, install the contrib package that matches your PostgreSQL major version before going further. Done when the extension is listed as available.
Add the library to shared_preload_libraries
In postgresql.conf, add pg_stat_statements to shared_preload_libraries. If other libraries are already listed, append it with a comma rather than replacing them. The module must be preloaded because it collects statistics from shared memory as statements run. Set the related tracking options, such as pg_stat_statements.track, only after you know what you need to capture. Done when the setting is saved in the file you will load on restart and you have a record of the previous value for rollback.
Restart the server in a planned window
Changing shared_preload_libraries takes effect only after a full server restart, and a reload is not enough. Schedule the restart in a maintenance window and tell application owners that connections will drop. Check that the server starts cleanly and that the log shows no errors about the library. Done when the server is back up and accepting connections after the restart.
Create the extension in the target database
Connect to each database you want to analyze and run CREATE EXTENSION pg_stat_statements. The view is created per database, but the statistics are collected for the whole instance, so one installation in a database is enough to read them there. Run this with a role that has the privileges needed to create extensions. Done when the command returns without error.
Verify the installed extension version
Run a query against pg_extension to confirm that pg_stat_statements is present and to record its version. Compare that version with the major version of your server so you know which columns the view exposes in your environment. Keep the output with your change record. Done when the query returns one row with the expected extension name and version.
Run a test query and confirm rows appear
Run a simple, identifiable query, such as a SELECT against a known table with a distinctive literal, then query pg_stat_statements for that statement text. You should see a row with a non-zero calls count and timing columns. Note that the view normalizes literals into placeholders, so search on the statement shape. Done when your test statement appears with calls of at least one.
Decide who can read the view
Statement text can contain sensitive literal values or table names, and the view is visible to users who have the right privileges. Decide which roles, such as a monitoring role or a DBA group, should be allowed to select from it, and grant access only to them. Confirm access by connecting as a role that should not have it and checking that the query is refused. Record the decision, because statement text is operational data that your access model should cover.
Confirm collection continues under real load
After a representative period of normal traffic, query the view again and check that calls and total time are growing for the statements your applications run. This confirms that the module is collecting from the workload you care about, not only from your test. Keep the reset decision for later, so the counters build a useful picture. Done when the top entries reflect known application queries.
Reading total time, mean time and planning versus execution
Build three rankings from the same view, because each answers a different question. Sorting by total_exec_time shows where the server spends its time overall, which is the cumulative load a tuning effort should target first. Sorting by mean_exec_time surfaces statements that are slow each time they run, which are usually candidates for an index, a rewrite or a plan fix. Sorting by calls finds chatty patterns, where the application sends a small query thousands of times per request, so the fix often sits in application code or batching. Illustrative example: a lookup that takes 2 ms but runs 4 million times a day can outrank a 900 ms report that runs twice a day. Column names differ between releases, so confirm the exact fields your version exposes before you write the queries.
When track_planning is enabled, the view also reports total_plan_time and mean_plan_time beside the execution figures, so you can split each statement's cost into planning and execution. A high planning share usually means the planner is doing a lot of work for each statement, such as joins across many tables, wide partitioned tables or statements that are rebuilt often. The fixes then live in schema and query shape: partition pruning, fewer joins, or how the driver uses prepared statements. A high execution share points at the work the plan performs, so the questions move to row estimates, indexes and data volume, which is the territory of plan analysis with EXPLAIN ANALYZE. Planning tracking adds some overhead, so turn it on deliberately and confirm the default and cost for your version.
Every figure in these views is cumulative since the last reset, so a ranking means nothing until you know its window. Record the stats_reset time from pg_stat_statements_info (confirm that your version provides it) and note it beside each report. A query that dominates the list may be a one-off batch job, and a window that is too short can hide a weekly report entirely. Take two snapshots of the view and subtract them, or reset at the start of a planned window and read the ranking at its end. Calling pg_stat_statements_reset() discards history for every user of the database, so agree the timing with the team, save the previous ranking, and avoid resets while an incident is still under investigation.
Resetting statistics and capturing a clean measurement window
This sequence gives the team a known starting point for pg_stat_statements, a fixed period of representative load, and a saved ranking that can be compared with later measurements. Each step has an owner and a check, so the backlog is built from data the team trusts.
Agree the measurement window with the team
Before anyone runs a reset, the DBA or platform owner agrees with application, release and on-call teams when the window starts and ends, which workloads must be running inside it, and who can tell the others if something unusual happens. Resets affect the statistics every team reads, so a reset without notice can disrupt a shared investigation. The step is done when the window, its owner and the workloads in scope are written down in the change or ticket record.
Confirm pg_stat_statements is loaded and check its scope
Confirm that the extension is installed in the database you are measuring, that it is listed in shared_preload_libraries, and that the server has been restarted since that change. Then check the reset function's documentation for the installed PostgreSQL version, because pg_stat_statements_reset() clears entries for all users and databases unless its arguments narrow the scope, and the exact arguments depend on the version. Record the version and the scope you will use. The step is done when a simple query against the view returns rows for the workload you expect.
Take a pre-reset snapshot of the current ranking
Before resetting, export the current top entries ordered by total time and by mean time to a file or a table that the team can keep. The old counters are lost at reset, so this snapshot is the only record of the period that came before, and it is useful when someone asks whether a problem started after a deployment. Store the query text, calls, total and mean execution time, and the query ID with a timestamp and the server version. The step is done when the export has been opened and its row count matches the view.
Reset the statistics at the agreed start
At the start of the agreed window, the owner runs pg_stat_statements_reset() with the scope confirmed in step two and notes the exact time. Avoid resetting in the middle of a batch job, a large migration or a planned load test unless that is the workload under study. The step is done when a query against the view returns only the entries that have run since the reset, with small call counts and a recent stats reset time where the installed version reports one.
Let the representative workload run
Keep the window open long enough for the normal daily cycle to run, including peak traffic, scheduled jobs and reporting queries, because a ranking taken during a quiet period will hide the queries that matter most. Ask the application team to confirm that the workload they expect actually ran, and check the call counts on known endpoints. The step is done when the owner and the application team agree that the window captured a representative period and nothing unusual distorted it.
Capture the ranking at the end of the window
At the agreed end time, run the same ranking queries as in the pre-reset snapshot, ordered by total execution time, mean execution time and call count, and save the results with the window start and end times, the server version and the PostgreSQL configuration relevant to statistics. Keep the query IDs, because they let you match entries across snapshots as long as the server version and query text are unchanged. The step is done when the saved file contains the start time, end time and at least one row per ranking.
Schedule recurring snapshots for trend comparison
A single window shows one period, so the team should decide whether to take snapshots on a fixed schedule, such as at the end of each business day or week, and whether to reset between them. Scheduled snapshots without resets let you calculate differences between two points in time, which avoids losing history at each reset. Confirm how long snapshots are kept and who can read them, because query text can contain sensitive values. The step is done when the schedule, retention and access rules are documented and the first scheduled snapshot has run.
Hand the saved ranking to the tuning backlog
The owner shares the saved ranking with the teams that own the top queries and records which entries will be investigated, with the window dates and version attached so later comparisons are fair. Each entry on the backlog should reference its query ID and the snapshot it came from. The step is done when every top entry has an owner or a documented reason it is excluded, and the snapshot is linked from the backlog.
How ranked query data becomes a tuning backlog
The flow starts with enabling pg_stat_statements and running the real workload through a fixed window. A ranked snapshot is then taken and each top entry is classified as planning-bound, execution-bound or call-volume-bound. Each class routes to a different next step: plan analysis, index review, an application change or a configuration review. Every change ends with a new snapshot of the same window, so the effect on the ranking can be checked before the item leaves the backlog.
Ranked statistics move through classification into fixes, each verified by a new snapshot.
Security and operational considerations for query statistics
The statistics that make pg_stat_statements useful also record query text, timings and schema details, so they need the same care as the data they describe. The cards below cover who can read the view, what the extension costs to run, how it is configured and kept current, and what happens to exported snapshots.
Query text can expose literals
pg_stat_statements normalizes queries by replacing constant values with placeholders, but normalization can miss literals in some statement shapes, and identifiers such as table and column names remain visible. Before granting access, review sample rows from the view on a non-production copy and look for account numbers, email addresses, tokens or personal data in the query column. If you find them, change the application to use bind parameters and retest the view contents.
pg_stat_statements docsRestrict who reads the view
Anyone who can query the statistics view can see the text of other users' statements, so treat it as sensitive data rather than as a dashboard table. Limit SELECT to a monitoring role that your operations team controls, and confirm that application roles cannot read it through a shared schema or a broad default privilege. Record who holds the role in your access review, since membership changes are the usual way this grant drifts.
Role grants in regulated environments
In regulated environments, the monitoring role should be documented as a privileged access path, with an owner, a justification and a review cycle that matches your access control policy. Ask your auditor which evidence they expect, such as role membership exports and change records. Keep the grant separate from superuser access and from the role that runs schema changes, so one account cannot both read the statements and alter the workload.
Measure the overhead before you trust it
The extension keeps its counters in shared memory and updates them on every statement execution, which adds some tracking cost and a fixed memory allocation sized by its configuration parameters. Measure the effect with a load test that resembles production, comparing latency and throughput with the extension loaded and not loaded. Also confirm that the number of tracked statements is large enough for your workload so that useful entries are not evicted.
Plan restarts for preload changes
The module must be listed in shared_preload_libraries, and changing that list requires a server restart, so schedule it in the same window as other restart-dependent changes. Changing the tracking settings also needs a restart, while enabling the extension in a database is a SQL step that needs no restart. Record which parameters require a restart in your change template, and test the sequence on a standby first when the primary serves live traffic.
Snapshots and retention
Exported snapshots of the view carry query text and schema names, so they become a data store of their own with their own retention, encryption and access rules. Decide how long snapshots are kept, where they are stored, who can restore them, and when they are deleted, and align that with your data classification. Keep the extension version aligned with the PostgreSQL major version after upgrades by running the extension update step during the upgrade plan, because a stale extension can break the view definition after a major upgrade.
Questions teams ask before enabling pg_stat_statements or hiring help
What does enabling pg_stat_statements cost in overhead and effort?
The extension adds a small amount of bookkeeping to each statement the server runs, and the main effort is a configuration change and a restart. The overhead depends on how many distinct statements the workload produces, how much pg_stat_statements.max is set to, and whether pg_stat_statements.track is set to all, which also records statements inside functions. Teams should measure the effect on a staging copy with a representative load before turning it on in production, and confirm the setting names and defaults for the PostgreSQL version they run in the official documentation.
How long do enabling and the first analysis take?
Enabling the extension is quick, but the first useful ranking needs a window of real traffic, so the calendar time is set by the workload rather than by the install. The duration depends on how often the slow path runs (a nightly batch job needs a full cycle to show up), how many distinct queries the application issues, and how many people must review the results before changes are agreed. Ask for a written plan that separates the install, the observation window and the analysis, and that names who signs off on each step.
What does the team need to provide before the work starts?
Three things usually decide how fast the work moves:
- Access: a role that can create the extension, read
pg_stat_statementsviews and read server configuration, plus shell access to the host if the change needs a configuration file edit. - A workload window: a period when the normal peak and batch jobs run, so the statistics reflect real use.
- A restart window: enabling the module requires the server to load it at start, so a maintenance slot is needed, and it must be agreed with the owners of any dependent services.
Also name the people who can explain the application's query patterns, because the ranking alone does not show intent.
Can an internal team do this without outside help?
Yes, many teams can enable the extension, read the top entries and open tickets against the slowest statements without outside help. The work gets harder when the data is ambiguous, when several applications share one cluster, or when changes to indexes or queries need coordination with developers who own them. Outside help adds value mainly in building a repeatable process: deciding which entries matter, separating planning time from execution time, linking each entry to a test, and keeping the backlog current after each release. Teams should decide which of these skills they already have.
How does pg_stat_statements relate to a performance audit?
The extension is one input to a performance audit, not a substitute for one. An audit usually reviews configuration and hardware, the top queries recorded by pg_stat_statements, index and bloat analysis, connection handling, and a prioritized fix list with the expected effect of each change. Running the extension yourself gives you the raw ranking; an audit adds the judgment about which entries to act on, in what order, and what evidence supports each recommendation. Ask any provider to state which of these areas its scope includes before agreeing a price.
Does the statistics data reset, and can it be trusted for long periods?
Statistics accumulate from the time the extension started or was last reset, so a ranking reflects a chosen window rather than the server's whole life. Resetting is useful before a release or a known change, because it removes old load from the picture. Teams should record when each reset happened so that comparisons are fair, and should confirm how the version they run exposes the reset function and the timestamps before building reports on them.
Who should be allowed to read the query text, and what security risk does it carry?
Query text can contain literal values, including personal data, account identifiers or other sensitive content, so access to the statistics views should be limited to the staff who need them. Restrict the roles that can read the views, review what the application puts into queries (for example, values placed directly in SQL text rather than bound as parameters), and set a retention rule for any exported reports. Confirm the exact privilege model for your PostgreSQL version and how your audit logging treats this data before sharing ranked lists outside the database team.
How DeployOpen scopes and delivers query analysis on your PostgreSQL
DeployOpen approaches slow query analysis as a fixed-scope piece of work inside your own infrastructure. We agree the databases, statistics collection, access and deliverables in writing first, then collect pg_stat_statements data from your server and turn the ranked results into a tuning backlog your team can act on.
How we scope
- Confirm which PostgreSQL clusters, versions and databases are in scope for the query ranking work.
- Agree who can enable the extension, reset statistics and read results on each server.
- Record the workload window, sampling period and how query text is handled before any collection starts.
How we build
- Enable pg_stat_statements in a change you approve, with the shared library and extension settings reviewed first.
- Capture total and mean time rankings over an agreed period, separating planning from execution time where the version supports it.
- Group entries by query ID, check for normalization noise and map each top entry to the application code or job that issues it.
How we hand over
- Deliver a written, prioritized backlog of top queries with the evidence, ranking method and reset dates used to build it.
- Document the collection setup, configuration keys, and the steps your team needs to repeat the ranking later.
- Walk your engineers through each entry so they can take the next step, such as reading EXPLAIN ANALYZE output, with clear ownership.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers after the initial analysis.
- Retest agreed queries after fixes are applied and record the before and after rankings in the written scope.
- Confirm with your PostgreSQL version and vendor documentation any behavior of pg_stat_statements that your environment depends on.

