The symptom
A query on PostgreSQL takes seconds where it should take milliseconds, or the database quietly eats CPU all day. Everything below ships with PostgreSQL; one piece, pg_stat_statements, has to be switched on first, and that takes a server restart.
Diagnose it
Rank the statements with pg_stat_statements
The module is in the standard contrib package but is not loaded by default. Add it to shared_preload_libraries, restart, then create the extension in the database you connect to. Until the library is preloaded, querying the view fails with pg_stat_statements must be loaded via "shared_preload_libraries". Managed services (RDS, Cloud SQL, Azure) usually preload it already, so only the CREATE EXTENSION step is left:
-- postgresql.conf, then restart:
-- shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT calls,
round(mean_exec_time::numeric, 1) AS mean_ms,
round(total_exec_time::numeric) AS total_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Total time finds the queries that hurt the server; mean time finds the ones that hurt your users. A query called 40,000 times a day at 3 ms each costs more than the nightly report that takes a minute. Constants are replaced with $1, $2 im query text, so every run of the same statement shape lands in one row. The column names above are PostgreSQL 13 and later; older versions call them total_time und mean_time. Seeing other users' query text needs superuser or the pg_read_all_stats role.
Read the plan with real timings and buffers
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total, c.name
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at >= now() - interval '7 days';
Three things to check, in order: where the plan scans (Seq Scan on a big table is the usual suspect), where the estimate diverges from the actual rows (a bad row estimate sends the planner down the wrong path), and where the buffers come from (hit= was found in shared_buffers; read= had to be fetched from the operating system, either its page cache or the disk - a hot query should be nearly all hits). EXPLAIN ANALYZE really runs the statement, so wrap writes in BEGIN; ... ROLLBACK;. From PostgreSQL 18, BUFFERS is included automatically with ANALYZE. Paste the plan into the query plan viewer for a readable rendering, and format the SQL with the SQL-Formatter if the query itself is a wall of text.
Check what the tables are doing
SELECT relname, seq_scan, seq_tup_read,
idx_scan, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY seq_tup_read DESC
LIMIT 10;
A large seq_tup_read with a small idx_scan means queries are crawling the heap because no index matches them. A growing n_dead_tup with a stale last_autovacuum means bloat, which makes every scan slower for everyone.
Look for lock waits when it is intermittent
SELECT pid, wait_event_type, wait_event, state, left(query, 60) AS query
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
A query that is usually fast but sometimes hangs is almost always waiting on a lock, not on the planner - see the blocking and deadlocks guide for who is holding it.
Fix it
Index what the plan scans. For the pending-orders example, one index carries the whole plan: equality predicate first, range last, and every other column the query reads from orders as INCLUDEs (PostgreSQL 11+) so the plan can become an Index Only Scan:
CREATE INDEX CONCURRENTLY idx_orders_status_created
ON orders (status, created_at DESC)
INCLUDE (id, customer_id, total);
CONCURRENTLY matters on any table people write to - a plain CREATE INDEX blocks inserts, updates and deletes until it finishes. It cannot run inside a transaction block, and if it fails it leaves an INVALID index behind that you must drop. Leave out any column from the INCLUDE list and the plan falls back to an Index Scan that visits the heap for each row. An Index Only Scan also depends on the visibility map, so a table that autovacuum has not processed recently shows a high Heap Fetches count in the plan.
Give the planner honest statistics. The default default_statistics_target of 100 is fine for most columns; for a skewed column whose rare values matter, raise it for that column only:
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 500;
ANALYZE orders;
Reclaim the bloat. Wenn n_dead_tup dwarfs n_live_tup, tune autovacuum on that table (ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01);, down from the default 0.2) rather than scheduling manual VACUUMs. Then check that nothing is holding back cleanup: an old xact_start in pg_stat_activity, a session idle in transaction, or a stale replication slot keeps every dead row since then from being removed.
Size memory for the working set. Persistent read= buffers on hot tables mean the cache is too small - the memory pressure guide walks through shared_buffers, work_mem and what to measure before changing them.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Preload pg_stat_statements (restart), CREATE EXTENSION, and let it accumulate at least a day of history.
- List the top 10 by total_exec_time and by mean_exec_time; they are usually different lists.
- EXPLAIN (ANALYZE, BUFFERS) the top offender and note every Seq Scan on a table over ~10k rows.
- Check estimated vs actual rows on each node; diverging estimates mean statistics work first.
- Create the covering index CONCURRENTLY for the dominant scan pattern.
- Re-run the EXPLAIN and confirm the Seq Scan became an Index Scan or Index Only Scan and the buffer counts dropped.
- Review pg_stat_user_tables weekly for dead-tuple growth and stale autovacuum timestamps.
Questions that come up
Why does EXPLAIN ANALYZE take longer than the query itself?
ANALYZE really executes the statement, and the instrumentation costs extra per row - on big sorts and hashes the overhead is noticeable. Wrap the statement in BEGIN/ROLLBACK when profiling writes so the changes are undone, or run it on a replica.
The planner uses a Seq Scan even though an index exists. Why?
Usually one of three things: the predicate does not match the index's leading column, the planner believes the scan will return most of the table (check the row estimates), or the column types do not match so an implicit cast blocks the index. EXPLAIN's filter condition tells you which - the index-not-used guide walks through each.
How do I find queries that got slower over time?
pg_stat_statements is cumulative: it survives a clean restart (pg_stat_statements.save is on by default) and only resets when you call pg_stat_statements_reset() or the server crashes. It has no history of its own, so snapshot it into a table on a schedule and diff the snapshots, or set log_min_duration_statement and feed the log to pgBadger for trending. A query whose mean time crept up while its calls stayed flat is a plan or bloat problem, not a traffic problem.
Is VACUUM FULL a normal maintenance task?
No - it takes an ACCESS EXCLUSIVE lock that blocks even reads, and rewrites the whole table, needing free disk space for the new copy. Plain VACUUM, which autovacuum runs, makes dead space reusable without that lock. Treat VACUUM FULL as a one-off repair for extreme bloat, and fix the underlying problem (long transactions, undersized autovacuum) instead of scheduling it.
Can I read execution plans without a database connection?
Yes. Paste the EXPLAIN output into SQLly's free query plan viewer at /tools/query-plan-viewer; it renders the tree in your browser. The SQLly desktop app has the same plan viewer built in next to the query editor.