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 thandeadlock_timeoutfor 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_eventNULL — actually running on CPU.wait_event_type = 'Lock'— waiting on another backend. Pair withpg_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?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
MySQL, PostgreSQL, Redis, and MongoDB End-of-Life Dates in 2026
Four major open source databases are hitting end-of-life milestones in 2026, and MySQL 8.0 has already crossed that line. Here's a practical, code-first look at how to audit what you're running, back it up properly, and migrate before the risk compounds.