Skip to content

Lesson 7 of 14 · 16m

Finding the Slow Query: pg_stat_statements and Friends

You can't EXPLAIN a query you haven't found — pg_stat_statements, auto_explain, log_lock_waits, and pg_stat_activity tell you what to fix before you fix it.

The previous lesson teaches you to read a plan. This one is the step nobody writes down: in production you don't know which query deserves an EXPLAIN. The complaint is "the app is slow," not "SELECT ... WHERE user_id is a seq scan." Finding the offender is its own discipline, and Postgres ships the instrument for it as an extension most people never load.

pg_stat_statements

CREATE EXTENSION pg_stat_statements;

It needs shared_preload_libraries = 'pg_stat_statements' and a restart — plan that restart during a maintenance window, not during the incident. Once loaded, it normalizes every query (literals become $1, so WHERE id = 5 and WHERE id = 9 aggregate into one entry) and tracks calls, total_exec_time, mean_exec_time, rows, and buffer reads per normalized query.

SELECT query, calls, total_exec_time, mean_exec_time,
       shared_blks_read, shared_blks_hit
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

The ordering choice is the first diagnostic. Sort by total_exec_time and you find the queries doing the most aggregate damage — often the cheap query firing ten thousand times a minute, which is an N+1 or a missing cache, not a bad plan. Sort by mean_exec_time and you find the genuinely slow individual queries that deserve EXPLAIN ANALYZE. Different lists, different fixes. pg_stat_statements_reset() clears the stats — run it after a fix ships, or you're averaging today's good numbers against last month's bad ones.

The log path

log_min_duration_statement = 500 logs every statement over 500ms — the cheap way in, no restart on some managed services (it's a reloadable GUC on RDS and friends). auto_explain goes further: preload it, set auto_explain.log_min_duration and auto_explain.log_analyze, and slow queries log their actual plans — estimated-vs-actual rows included. Now the incident report contains the plan, not just the complaint.

Two logging knobs people miss:

  • log_lock_waits (14+) — logs when a statement waits longer than deadlock_timeout for a lock. Half of "queries are slow" incidents are queries waiting, and this is how you see it.
  • log_min_duration_sample (13+) — samples a fraction of fast statements so a 1ms threshold doesn't drown your logs.

Watching it live

pg_stat_activity is the now-view: every backend, its state, its current query, query_start, wait_event. The patterns worth memorizing:

SELECT pid, state, wait_event_type, wait_event,
       now() - query_start AS age, query
FROM pg_stat_activity
WHERE state <> 'idle';
  • state = 'active', wait_event NULL — actually running on CPU.
  • wait_event_type = 'Lock' — waiting on another backend. Pair with pg_blocking_pids(pid) to find who's holding it.
  • state = 'idle in transaction' — the vacuum blocker and lock-holder from lesson one, sitting there holding its snapshot open. pg_terminate_backend(pid) is the tool when it won't leave.

Two more columns in pg_stat_statements earn their space: shared_blks_read vs shared_blks_hit shows which queries actually miss the cache (a query can be fast and still do a million buffer reads — that's tomorrow's incident), and track_io_timing = on splits execution time into CPU vs disk waits, at a small per-call clock cost. The extension normalizes away constants, so a WHERE email = query aggregates regardless of the address — which is the whole point, but it also means you can't reconstruct the literal from the stats table; the raw text only lives in the query log or pg_stat_activity.

Postgres 16 added pg_stat_io, which finally answers "is it the disk?" per-backend, per-object, per-operation — reads, writes, evictions, fsyncs. Before 16 that required guessing from pg_statio per-table stats or OS-level iostat.

The practice

Load pg_stat_statements everywhere; it's a one-time restart for permanent visibility. Review the top-10 by total time weekly, reset after fixes. Set log_min_duration_statement to a number that catches real pain without spamming — 500ms is a sane start for OLTP, lower if your users notice faster. And when someone reports "the database is slow," the first query you run is on pg_stat_activity, not EXPLAIN: half the time nothing is running — everything is waiting, and that's a different fix entirely.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.