Skip to content

Find slow queries in PostgreSQL with pg_stat_statements

Enable pg_stat_statements and rank queries by total_exec_time, mean_exec_time, and calls to find the statements that actually cost your database the most.

pg_stat_statements is the extension that tells you which query is actually slow. It watches every statement your database runs, strips out the literal values so WHERE id = 42 and WHERE id = 99 count as the same query, and keeps a running total of how long each shape took, how often it ran, and how many rows it touched. You then sort that table by total time to find the query that costs your server the most cumulative work — which is almost never the one you’d guess. This is aggregate slow-query discovery; once it names the offender, you reach for EXPLAIN ANALYZE to read that one plan and fix it.

What you’ll accomplish

  • Add pg_stat_statements to shared_preload_libraries and load it with one restart.
  • Create the extension and confirm counters are accruing.
  • Rank queries by total_exec_time, mean_exec_time, calls, and rows.
  • Tell a “slow every time” query apart from a “fast but run a million times” query.
  • Reset the counters cleanly so a before/after change is measurable.

Prerequisites

  • PostgreSQL 13 or newer for the column names in this guide. pg_stat_statements ships with every version, but in 9.4 through 12 the timing columns were named total_time, mean_time, min_time, max_time. Version 13 renamed them to total_exec_time, mean_exec_time, and so on, and split out separate planning-time columns. If you are on 12 or older, drop the _exec from every column name below.
  • Superuser or ALTER SYSTEM access. Changing shared_preload_libraries requires editing server configuration, and CREATE EXTENSION requires a superuser or a role with the right privilege.
  • The ability to restart the server once. shared_preload_libraries is only read at startup — a reload is not enough. Plan a short maintenance window.
  • The contrib package installed. On Debian and Ubuntu that is postgresql-contrib (or it is bundled with postgresql-16); on RHEL-family systems it is postgresql16-contrib. Managed platforms (RDS, Cloud SQL, Azure) ship it already — you enable it through a parameter group instead of editing files.

How it works

The extension hooks into the executor. Every time a statement finishes, it takes the query text, replaces every constant with a placeholder like $1, and computes a hash of that normalized text. That hash is the identity of the query. All the statements that share a shape land on the same row in a fixed-size table held in shared memory, and their counters — calls, total_exec_time, rows, and more — are summed into it.

Diagram of raw application queries being normalized and summed into the pg_stat_statements shared-memory view

Because the counters are cumulative and live in shared memory, they survive across all connections and keep climbing until you call pg_stat_statements_reset() or the server restarts. The table is capped at pg_stat_statements.max entries (5,000 by default); when it fills, the least-executed entries are evicted to make room. You read the data through a view, also named pg_stat_statements, that joins those counters to the stored query text. Sorting that view is the whole technique.

Step-by-step

1. Add the extension to shared_preload_libraries. Use ALTER SYSTEM so the setting lands in postgresql.auto.conf and survives config regeneration. If the parameter already lists other libraries, include them all in one comma-separated string — this setting is not additive.

ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';
ALTER SYSTEM

2. Restart the server. A reload will not pick this up; preloaded libraries load only at startup.

sudo systemctl restart postgresql
(no output on success — the shell returns to the prompt)

Confirm the library is now loaded before going further:

SHOW shared_preload_libraries;
 shared_preload_libraries
--------------------------
 pg_stat_statements
(1 row)

3. Create the extension in the database you want to watch. The library is loaded process-wide, but the view and functions must be registered per database.

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION

4. Generate some traffic, then rank by total execution time. This is the query you will run over and over. total_exec_time is in milliseconds; dividing by 1000 gives seconds, which is easier to read.

SELECT
  round(total_exec_time::numeric, 1) AS total_ms,
  calls,
  round(mean_exec_time::numeric, 2) AS mean_ms,
  rows,
  left(query, 60) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 5;
 total_ms  | calls  | mean_ms | rows    |                    query
-----------+--------+---------+---------+----------------------------------------------
 412803.5  | 128441 |    3.21 | 128441  | SELECT * FROM orders WHERE customer_id = $1
 201558.0  |    842 |  239.38 |   84200 | SELECT o.*, c.email FROM orders o JOIN cust
  90114.7  | 512006 |    0.18 |  512006 | SELECT id FROM sessions WHERE token = $1
  44201.2  |     31 | 1425.85 |    2170 | SELECT count(*) FROM events WHERE created_a
   1120.4  |   9004 |    0.12 |    9004 | UPDATE carts SET updated_at = now() WHERE i
(5 rows)

5. Read the ranking two ways. The top row costs the most total time (412 seconds) but each call is only 3.21 ms — it is slow in aggregate because it runs 128,441 times, so the fix is likely caching or a chattier-than-needed access pattern, not the query itself. The fourth row runs only 31 times but averages 1,425 ms per call; that one is genuinely slow per execution and is the best candidate for EXPLAIN ANALYZE. Sort by mean_exec_time to surface those:

SELECT
  round(mean_exec_time::numeric, 1) AS mean_ms,
  calls,
  left(query, 60) AS query
FROM pg_stat_statements
WHERE calls > 10
ORDER BY mean_exec_time DESC
LIMIT 5;
 mean_ms | calls |                    query
---------+-------+----------------------------------------------
  1425.8 |    31 | SELECT count(*) FROM events WHERE created_a
   239.4 |   842 | SELECT o.*, c.email FROM orders o JOIN cust
    18.7 |  4120 | SELECT * FROM invoices WHERE status = $1 AN
     3.2 | 128441| SELECT * FROM orders WHERE customer_id = $1
     0.2 | 512006| SELECT id FROM sessions WHERE token = $1
(5 rows)

The WHERE calls > 10 filter drops one-off queries whose single slow run is noise. Now you have a named target: take the full text of that top query and run EXPLAIN ANALYZE on it. See read a PostgreSQL query plan with EXPLAIN and EXPLAIN ANALYZE for what to do with the plan once you have it.

Four-step workflow from ranking queries by total time to picking the worst, running EXPLAIN ANALYZE, and fixing then resetting

Validate it works

Right after CREATE EXTENSION the view has only a handful of rows — its own bootstrap queries. Run something against a real table, then confirm the row count climbs:

SELECT count(*) FROM pg_stat_statements;
 count
-------
    47
(1 row)

A number that grows as your application runs means the counters are recording. For the day-to-day view, the top-N-by-total-time query in step 4 is the one to keep handy. To make a change measurable, reset the counters, exercise the workload, then read the view — everything you see is now attributable to that window:

SELECT pg_stat_statements_reset();
 pg_stat_statements_reset
--------------------------

(1 row)

Troubleshooting

  • ERROR: pg_stat_statements must be loaded via shared_preload_libraries. You ran CREATE EXTENSION (or queried the view) without the library preloaded. Confirm SHOW shared_preload_libraries; lists it, and remember that changing the setting requires a full restart, not a pg_reload_conf() or SELECT pg_reload_conf(). A reload silently leaves the old value in place.

  • column "total_exec_time" does not exist. You are on PostgreSQL 12 or older, where the columns are total_time, mean_time, min_time, and max_time with no exec/plan split. Either drop the _exec from the column names, or upgrade. On 13+ there are both total_plan_time and total_exec_time; this guide sorts on execution time because that is where query cost usually lives.

  • The view is empty or nearly empty. Counters only accrue for statements that finish after the extension is loaded and created, and by default only top-level statements are tracked. If you loaded it during a quiet period, generate real traffic first. To also capture statements nested inside functions and procedures, set pg_stat_statements.track = all (the default is top):

    ALTER SYSTEM SET pg_stat_statements.track = 'all';
    SELECT pg_reload_conf();

    Unlike shared_preload_libraries, the track and max sub-settings take effect on reload — except pg_stat_statements.max, which needs a restart because it sizes the shared-memory table.

  • The interesting query dropped out of the view. The table holds at most pg_stat_statements.max entries. On a busy database with thousands of distinct query shapes, rarely-run statements get evicted. Raise the cap (ALTER SYSTEM SET pg_stat_statements.max = 10000; then restart) if you are losing entries you care about.

  • Reset wiped numbers a teammate was watching. pg_stat_statements_reset() is global by default and clears everything for every user of that database. Coordinate before resetting on a shared server, or on PostgreSQL 12+ reset a single statement by passing userid, dbid, and queryid arguments instead of zeroing the whole table.

When this is the wrong approach

pg_stat_statements is a discovery tool for aggregate cost. It is the wrong tool when you already know the single query and just need its plan — go straight to EXPLAIN ANALYZE. It also does not capture individual slow executions with their actual parameters; for “this specific request at 2:14 a.m. was slow,” you want log_min_duration_statement writing slow statements to the server log, or the auto_explain module. And a query that is fast in pg_stat_statements but slow for users may be waiting on locks or a saturated connection pool rather than on execution — the extension measures time spent executing, not time spent queued. Bloat from missing maintenance can also inflate execution time across the board; see PostgreSQL VACUUM and autovacuum. The official reference is the pg_stat_statements documentation.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.