Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

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.

  1. What two steps enable pg_stat_statements?
  2. total_exec_time vs mean_exec_time — which finds what?
Show the answers
  1. shared_preload_libraries at server start, then CREATE EXTENSION in the database.
  2. 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.

Search the guide