Skip to content

pg_stat_statements for PostgreSQL query tuning

Use pg_stat_statements to find slow queries, regressions, and write-heavy hot paths in PostgreSQL — install, key queries, and the reset cadence we run.

pg_stat_statements records every distinct query the server has run, with totals for execution time, calls, rows, and I/O. It is the single most important observability tool in PostgreSQL — it tells you which queries to tune, which got slower, and which are silently doing 90% of your write traffic. This article covers the install, the queries we actually use, and the reset cadence that keeps the data useful.

How to verify

Confirm the extension is loaded and check what it sees:

psql -c "SHOW shared_preload_libraries;"
psql -c "SELECT * FROM pg_available_extensions WHERE name='pg_stat_statements';"
psql -c "SELECT count(*) FROM pg_stat_statements;"
psql -c "SELECT pg_stat_statements_reset();" 2>/dev/null || \
psql -c "SELECT pg_stat_statements_reset()::text IS NOT NULL AS ok;"

A typical OLTP database accumulates 2000-20,000 distinct normalised queries — if you see 100, the extension probably isn’t capturing or is being reset.

What’s happening

pg_stat_statements hooks into the executor. Every time Postgres executes a query, it normalises the query text (replacing literals with $1, $2, etc.), hashes the normalised form, and updates the entry in pg_stat_statements with cumulative stats: total execution time, calls, rows, shared block reads/writes/dirties, temp file usage, WAL bytes. The data is in shared memory and persists across reconnects but not across restarts (it’s flushed to disk every five seconds since PG 12).

pg_stat_statements.max controls how many distinct queries are tracked (default 5000; we run 10000+ on busy databases). When the limit is hit, the least-used entries are evicted — high query churn (lots of dynamically-generated SQL) can make the table less useful.

You can scope what’s tracked: pg_stat_statements.track = 'all' includes nested queries inside functions; 'top' (default) only counts top-level statements. track_utility = on includes DDL and VACUUM; turn it off if it adds noise.

The procedure

  1. Install and enable:

    sudo -u postgres psql -c "ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';"
    sudo systemctl restart postgresql@16-main

    Then in each database that needs stats:

    CREATE EXTENSION pg_stat_statements;

    The extension lives in one database but the tracking is server-wide; CREATE EXTENSION is just for the view access.

  2. Tune the settings:

    ALTER SYSTEM SET pg_stat_statements.max = 10000;
    ALTER SYSTEM SET pg_stat_statements.track = 'top';
    ALTER SYSTEM SET pg_stat_statements.track_utility = on;
    ALTER SYSTEM SET pg_stat_statements.save = on;
    SELECT pg_reload_conf();
  3. The “top queries by total time” query — your daily driver:

    SELECT
      substring(query, 1, 80) AS query,
      calls,
      round(total_exec_time::numeric, 1)         AS total_ms,
      round(mean_exec_time::numeric, 2)          AS mean_ms,
      round((100 * total_exec_time /
             sum(total_exec_time) OVER ())::numeric, 1) AS pct_total,
      rows
    FROM pg_stat_statements
    WHERE query NOT LIKE '%pg_stat_statements%'
    ORDER BY total_exec_time DESC
    LIMIT 20;

    The query that spent the most cumulative time is the highest-value tuning target — fixing a 100ms query that runs 100,000 times a day saves more than fixing a 30-minute query that runs once.

  4. Find regressions by snapshotting the stats and comparing:

    CREATE TABLE pgss_snap_t1 AS SELECT * FROM pg_stat_statements;
    -- wait an hour or run a deploy
    CREATE TABLE pgss_snap_t2 AS SELECT * FROM pg_stat_statements;
    
    SELECT a.queryid,
           substring(a.query, 1, 80) AS query,
           (b.total_exec_time - a.total_exec_time) AS delta_ms,
           (b.calls - a.calls) AS delta_calls
    FROM pgss_snap_t1 a JOIN pgss_snap_t2 b USING (queryid)
    WHERE (b.calls - a.calls) > 0
    ORDER BY delta_ms DESC LIMIT 20;

    A query whose mean_exec_time jumped 10x after a deploy is the smoking gun.

  5. For write-heavy workloads, sort by WAL or shared blocks:

    SELECT substring(query, 1, 80) AS query,
           calls,
           pg_size_pretty(wal_bytes) AS wal,
           pg_size_pretty(shared_blks_dirtied * 8192) AS dirtied
    FROM pg_stat_statements
    ORDER BY wal_bytes DESC LIMIT 20;

    Reveals the queries driving WAL volume and write amplification.

  6. Reset on a schedule. pg_stat_statements_reset() clears the table. We run it nightly on busy hosts so day-over-day comparisons are clean, and on deploys so the new code’s stats aren’t contaminated by the old.

Common pitfalls

  • Different literals produce the same normalised query — WHERE id IN (1,2) and WHERE id IN (1,2,3,4) are different queryids in older Postgres, the same since 13. Verify before drawing conclusions.
  • Resetting clears everything; if you want per-deploy stats, snapshot first.
  • track = 'all' adds nested function calls — useful for analyzing PL/pgSQL hotspots but multiplies the entry count.
  • pg_stat_statements doesn’t include plan details; pair with auto_explain for queries you want plans for.
  • The extension’s shared memory is sized at startup — pg_stat_statements.max cannot be changed without restart.

In the engagements we run, pg_stat_statements is enabled on every Postgres host from day one. We pair it with pgBadger for the in-time view of what happened, with auto_explain for plan capture on slow queries, and with a small dashboard that surfaces the top 20 by total time, by mean time, and by WAL bytes. The combination is what makes Postgres tuning a routine rather than a quarterly fire drill. For the operating model behind a tuned Postgres footprint, see managed operations.