Topic 4 of 5 · 5 min read
Finding slow PostgreSQL queries
Goal: Use pg_stat_statements output to rank the queries worth fixing and choose the fix for the most expensive one.
Rank queries by total time from pg_stat_statements, then read the plan of the top one with EXPLAIN ANALYZE before changing anything. The slowest single query is rarely the one costing you most. A modest query called a million times is.
Check yourself · 1 of 3
Which pg_stat_statements column best ranks queries by overall load on the server?
Why it matters
Slow databases get "fixed" by guesswork: a new index here, a bigger instance there. AI assistants will happily suggest an index for any query you paste. Measurement tells you which query matters and what is wrong with it.
How to do it
- Turn on pg_stat_statements. Add it to
shared_preload_libraries, restart, thenCREATE EXTENSION pg_stat_statements. It groups queries by normalised text, with parameters removed. - Rank by total time. Order by
total_exec_timedescending. Readcalls,mean_exec_timeandrowsbeside it. High total with high calls is an overall load problem. High mean with few calls is a single bad query. - Explain the top one.
EXPLAIN (ANALYZE, BUFFERS)runs the query and shows actual timing. Compare estimated rows to actual rows: a big gap means stale statistics (runANALYZE). A sequential scan that discards most rows suggests a missing index. Remember ANALYZE executes the statement, so wrap writes in a transaction you roll back. - Check bloat and vacuum. Updates and deletes leave dead rows. Autovacuum cleans them. A table with a long-running transaction open can stop cleanup, so it keeps growing and scans slow down. Look at
pg_stat_user_tablesforn_dead_tupandlast_autovacuum. - Pool connections. Each Postgres connection is a process with its own memory. Hundreds of app instances opening connections hurt more than they help. PgBouncer in transaction mode multiplexes many clients onto a few server connections, but session features such as session-level prepared statements and advisory locks need care.
- Set timeouts.
statement_timeoutstops runaway queries, andidle_in_transaction_session_timeoutstops forgotten transactions blocking vacuum.
Before and after
-- Weak: guess at an index for the slowest-looking query
CREATE INDEX ON orders (created_at);
-- Measure first
SELECT calls, round(total_exec_time) AS total_ms,
round(mean_exec_time::numeric,2) AS mean_ms, rows, left(query,60)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
What goes wrong
- Fixing the query with the worst mean. It runs twice a day while another costs 40 times more in total.
- Adding indexes for every plan. Each index slows writes and takes space.
- Reading EXPLAIN without ANALYZE. Estimates can be wildly off.
- Pooling that breaks sessions. Transaction mode drops session state between statements.
Examples
Reading a pg_stat_statements ranking
| Query | calls | mean ms | total ms |
|---|---|---|---|
| SELECT * FROM events WHERE user_id = $1 | 2,400,000 | 3.1 | 7,440,000 |
| SELECT ... report join ... | 40 | 5,200 | 208,000 |
The report query is the one people complain about. The events lookup costs about 35 times more in total. Check its plan first; saving one millisecond per call beats rewriting the report.
A plan that points to statistics, not indexes
Seq Scan on orders (cost=0.00..18334.00 rows=12 width=96)
(actual time=0.02..95.1 rows=48210 loops=1)
Filter: (status = 'pending')
The planner expected 12 rows and got 48,210. Run ANALYZE orders and re-check before adding an index; a stale estimate can pick a bad plan.
Key points
- Rank by total_exec_time first; a cheap query called very often can cost more than a rare slow one.
- EXPLAIN (ANALYZE, BUFFERS) shows real timings; a large gap between estimated and actual rows points to stale statistics.
- EXPLAIN ANALYZE actually runs the statement, so test writes inside a transaction you roll back.
- Dead rows from updates and deletes need vacuum; a long-open transaction can block cleanup and cause bloat.
- A pooler such as PgBouncer lets many app clients share few server connections, with limits in transaction mode.
- statement_timeout and idle_in_transaction_session_timeout contain runaway and forgotten queries.
Common mistakes
- Optimising the query with the highest single runtime instead of the highest total time.
- Adding an index suggested by an AI assistant without looking at the plan or the write cost.
- Running EXPLAIN ANALYZE on an UPDATE or DELETE outside a transaction.
- Opening hundreds of direct connections instead of using a pooler.
Check yourself · 2 of 3
EXPLAIN ANALYZE on an UPDATE statement is safe to run directly on production data.
Check yourself · 3 of 3
A plan shows the planner expected 12 rows but the scan returned 48,210. What is the best first step?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL: JSON types (opens in a new tab)DocsFree
jsonb versus json, the containment operator and the GIN operator classes.
- PostgreSQL: Full text search (opens in a new tab)DocsFree
tsvector, tsquery, ranking, configurations and indexes for text search.
- pgvector: open-source vector similarity search for Postgres (opens in a new tab)ToolFree
Vector types, HNSW and IVFFlat settings, filtering and the trade-offs of each index.
More for this topic
- PostgreSQL: pg_stat_statements (opens in a new tab)DocsFree
The columns that rank queries by total time, calls and rows.
- Using EXPLAIN (PostgreSQL documentation) (opens in a new tab)DocsFree
How to read plan nodes, estimated versus actual rows and timing.