← Lessons

quiz vs the machine

Silver1060

Databases

Identifying Slow Queries

Before you can tune a query you have to find the one that actually hurts, using cumulative cost rather than gut feeling.

4 min read · intro · beat Silver to climb

Start With Data, Not Hunches

The query that feels slow is rarely the one that costs the most. A report that runs once a day for two seconds matters far less than a lookup that runs ten thousand times a minute at fifty milliseconds. Tuning works best when you rank queries by total time, which is mean latency multiplied by call count.

Where the Numbers Live

  • Statistics views such as pg stat statements aggregate calls, total time, and mean time per normalized query.
  • Application metrics and traces show latency from the caller side, including network and pool wait.
  • The slow query log captures individual statements that cross a time threshold.

What to Look For

  • High total time means a strong tuning target even if each call is quick.
  • High mean time points at a single expensive statement.
  • High call count can hint at an n plus one or a missing cache.

A Simple Loop

Measure, pick the top offender by total time, fix it, then measure again. The ranking shifts after every fix, so always re sort.

Key idea

Find slow queries by ranking on total time, mean latency times call count, so you spend effort where it changes overall load the most.

Check yourself

Answer to earn rating on the learn ladder.

1. Why rank queries by total time rather than mean latency alone?

2. What might a very high call count for one query suggest?