Reading a Slow Query Log Without Fooling Yourself
Open any slow query log and the top entry will be something grotesque: a 40-second reporting query, an accidental cross join, a one-off migration. It will also, usually, not matter. Slow query logs rank by individual embarrassment. Production pain ranks by total cost — duration multiplied by frequency — and the two rankings barely overlap.
Normalize before you rank
The first step is always to group by query shape: strip the literals, collapse whitespace, and aggregate. Tools like pg_stat_statements or pt-query-digest do this for you. What emerges is unglamorous: the 300-millisecond query that runs ten thousand times an hour, quietly consuming more database than everything else combined. That is your actual problem, and it was sitting at rank forty.
Beware the average
A query with a mean of 5 ms and a p99 of 900 ms does not have a performance characteristic; it has two. Usually the slow tail is a different plan — a parameter value that flips the planner to a sequential scan, or a cache-cold path. Aggregates hide this. Look at the distribution, or at minimum the max alongside the mean, before concluding anything.
The log is a sample of a system
A query can be slow because the query is bad, or because the machine was busy checkpointing, or because a backup was streaming off the same disks. Correlate before you optimize: timestamp-align slow entries against checkpoints, backups, and deploys. We once spent a week "fixing" a query whose only defect was running at the same minute as a nightly job. The fix was a cron entry, not an index.
Read the log like an auditor, not a fan: totals over outliers, distributions over averages, and the system around the query before the query itself.