Part 18 / Topic 1 of 7
Finding slow queries
Tuning starts with which query — measured, not guessed. pg_stat_statements aggregates every statement the server runs: calls, total time, rows. It's a contrib module loaded at server start (shared_preload_libraries = 'pg_stat_statements' in postgresql.conf, restart) plus an extension in the database:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT count(*) > 0 AS collecting FROM pg_stat_statements;
CREATE EXTENSION
collecting
------------
t
(1 row)
From here, the ritual read — top time-eaters, normalised (literals folded to $1, so a thousand variants of one query aggregate together):
SELECT calls, round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
left(query, 60) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 3; -- output varies per run
calls | total_ms | mean_ms | query
---------+----------+---------+--------------------------------------------------------
1 | 734.3 | 734.33 | CREATE TABLE big_events AS +
| | | SELECT g AS id, (g % $1) + $2
2 | 139.5 | 69.73 | UPDATE readings SET value = value + $1
1 | 123.9 | 123.93 | ANALYZE
(1 row)
Sort by total_exec_time for the biggest bills (a 2 ms query called a million times outranks one 5-second report), by mean_exec_time for the painful individuals. The companion tool is log_min_duration_statement — set it to, say, 250ms and every slower statement lands in the server log with its parameters: the "what exactly was slow at 3 am" record. Together they answer the only question that matters before tuning: is this query worth my afternoon?
🧪 Quick quiz — answer from memory, then check.
- What two steps enable pg_stat_statements?
- total_exec_time vs mean_exec_time — which finds what?
Show the answers
shared_preload_librariesat server start, then CREATE EXTENSION in the database.- Total finds the aggregate bill-payers (fast-but-constant queries); mean finds individually slow ones.
Done here? The practice set for Part 18 — 5 exercises with solutions — is on the part page.