How to Use pg_stat_statements for Query Fingerprinting
Find the queries that cost the most with pg_stat_statements: normalized fingerprints, per-query timing and the limits of the view.
On this page
Introduction
A database with thousands of query shapes calls for a way to find which ones matter. Logging every query is too much data; profiling one at a time is too slow. PostgreSQL’s pg_stat_statements extension solves this by normalising each query into a fingerprint, so all executions of the same shape are aggregated, and tracking totals and timing per fingerprint. The result is a ranked list of the query shapes that consume the most time, which is where optimisation effort actually pays off.
What a Fingerprint Is
pg_stat_statements normalises a query by replacing the literals with placeholders, so SELECT * FROM orders WHERE id = 1, id = 2 and id = 999 all become the same normalised query. The extension then aggregates their executions, total time and rows under one row in the view.
This is what makes it useful at scale: you see the cost of a query shape, not of each individual query, so a shape executed a million times with a cheap value shows its true aggregate cost. Grouping by shape is the insight; without it you would be drowning in individual queries.
-- The same shape, normalised to one fingerprint (illustrative):
-- SELECT * FROM orders WHERE id = 1
-- SELECT * FROM orders WHERE id = 2
-- become:
-- SELECT * FROM orders WHERE id = $1
-- pg_stat_statements aggregates all executions of that shape into one row.
Enabling and Reading the View
Enable the extension (shared_preload_libraries or CREATE EXTENSION) and query the view. The essential columns are calls (how many times the shape ran), total_exec_time (the aggregate time), mean_exec_time (time per call) and rows (rows returned or affected). Ranking by total time finds the shapes that consume the most overall.
Rank by total time, not by mean, when you want to reduce overall load: a cheap query executed a million times can cost more in total than an expensive one executed once. Rank by mean when you are chasing a slow individual query. The two rankings answer different questions.
-- Top query shapes by total time (the overall-load view).
SELECT calls,
total_exec_time,
mean_exec_time,
rows,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
-- rank by total to reduce load; by mean to find a slow individual query
Interpreting the Columns
calls with a very high mean means the query has no index or a bad plan per call. A high total with a low mean means it runs many times and is individually cheap: index gains may be small, but batching or caching the shape may help a lot. rows per call tells you whether the query returns many rows or just a few.
The ratio of total_exec_time to the sum over all shapes tells you the shape’s share. A single shape consuming a large fraction is the priority; twenty shapes each consuming a percent are a grind, not an emergency. Use shares to decide where to spend effort.
# reading the numbers
high calls + high mean -> no index / bad plan per call (add an index)
high calls + low mean -> cheap but frequent: batch or cache the shape
high total (large share) -> top priority
rows >> 0 per call -> returns many rows: consider limiting/keyset
# a shape's share of total time is the priority signal
Resetting and Sampling
The statistics accumulate since the last reset. Reset them after a change to measure the effect on the shape you optimised, comparing the before and after statistics for a clean signal. Without a reset, old executions dilute the change.
Track the delta over a window rather than a single snapshot: take statistics at the start and end of a period and difference them, so a shape that was hot last week but is now fixed does not dominate. This is the same windowing discipline as any counter.
-- Reset to measure a change cleanly (do this deliberately)
SELECT pg_stat_statements_reset();
-- ... run the workload ...
-- then compare the shape's calls/mean against the pre-change numbers
-- or snapshot twice and difference the counters over a window
Finding the Plan Behind a Bad Shape
pg_stat_statements tells you which shape hurts; EXPLAIN (ANALYZE, BUFFERS) tells you why. Take the normalised query, substitute representative values, and run it with EXPLAIN to see the plan: a sequential scan where an index should be, a nested loop over a large set, a sort that should be an index order.
The extension does not store the plan, so the two tools are used together: rank by pg_stat_statements, then diagnose the top shapes with EXPLAIN and the planner statistics. This pairing is what turns the ranking into a fix.
-- Diagnose the top shape with a representative value:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;
-- look for: Seq Scan on a large table, a Sort, a nested loop over many rows
Limits of the View
pg_stat_statements has a finite size and evicts the least-executed shapes when it is full, so a rare but very slow query can be evicted before you see it. It also normalises some queries to the same fingerprint that are semantically different, and it tracks execution time, not wait time or lock contention.
It is a sampled, aggregated view, not a complete record: use it to find where the time goes, not to account for every millisecond. Complement it with detailed logging for the specific slow queries and with wait-event analysis for contention, which the view does not capture.
# limits to know
[ ] finite entries => rare-but-slow shapes may be evicted
[ ] some distinct queries share a fingerprint (over-normalisation)
[ ] tracks execution time, NOT wait time or lock contention
# use it to find where time goes; pair with logging + wait analysis
Common Pitfalls and Conclusion
Do not rank by mean alone and miss a cheap-but-frequent shape that dominates total time. Do not forget to reset before measuring a change. Do not treat the ranking as the diagnosis; the plan is the diagnosis. And do not assume it captures everything, because it evicts and aggregates.
pg_stat_statements fingerprints queries so the cost of a shape is visible, and ranking by total time points at where optimisation pays. Enable it, rank by total and by mean for different questions, reset to measure changes, diagnose the top shapes with EXPLAIN, and respect its limits. Then optimisation effort goes to the shapes that actually consume the database’s time.
Verify a fix by resetting the statistics and checking the shape’s total time after the change.
Sources: PostgreSQL: pg_stat_statements, PostgreSQL: EXPLAIN, PostgreSQL: Monitoring stats.
FAQ
- Should I rank by total or mean time?
- Rank by total_exec_time to reduce overall load, because a cheap query run often can cost more in total than an expensive rare one. Rank by mean_exec_time to find a slow individual query. The two rankings answer different questions.
- Why does my slow query not appear in pg_stat_statements?
- Possibly because the view is full and evicted the least-executed shapes, and a rare query is evicted first. Increase the view size, or use detailed logging for the specific slow query, and remember the view tracks execution time, not wait time.
Report a problem with this articleOpens a pre-filled issue on GitHub.