← Lessons

quiz vs the machine

Gold1390

Databases

Pg Stat Statements

Finding the queries that actually consume your database time across the whole workload.

5 min read · core · beat Gold to climb

Workload wide visibility

A single slow query is easy to spot, but the real cost often hides in a fast query run millions of times. The pg stat statements extension tracks execution statistics for every normalized query across the server.

How it normalizes

The extension groups queries by shape, replacing constants with placeholders. A query that differs only by its where value is counted as one entry, so you see total impact rather than scattered one offs.

For each normalized statement it records:

  • calls, the number of executions.
  • total exec time, the cumulative time spent.
  • mean exec time, rows returned, and cache hit information.

Using it

  • Sort by total exec time to find what dominates the workload, not just the single slowest run.
  • A query with low mean time but enormous call count can outweigh a rare expensive report.
  • Reset the statistics to measure a fresh window after a change.

This turns tuning from guesswork into a ranked list of where database time actually goes.

Key idea

Pg stat statements normalizes queries by shape and accumulates calls and timing, so sorting by total time reveals the statements that truly dominate your workload, including cheap queries run very often.

Check yourself

Answer to earn rating on the learn ladder.

1. How does pg stat statements group queries?

2. Why sort by total exec time rather than mean time?