Sub topic 5
Finding the Queries That Cost the Most Overall
Assume you know basic SQL, can use psql or another SQL client, and understand that PostgreSQL executes a query according to a query plan. This chapter uses the pg_stat_statements view. The view stores cumulative statistics for normalized SQL statements.
A query can be expensive in two different ways:
- It can take a long time each time it runs.
- It can run very often and consume a large amount of time in total.
This chapter focuses on the second case. These queries are called heavy hitters because their combined cost is large, even if each individual execution seems acceptable.
What total execution time means
The total_exec_time column is the sum of execution time for all recorded calls in one pg_stat_statements row. Its unit is milliseconds.
For example, a query with these values has two different costs:
calls = 10,mean_exec_time = 2,000 ms: about 20 seconds in total.calls = 100,000,mean_exec_time = 5 ms: about 500 seconds in total.
The second query is much cheaper per call, but it consumes more database time overall. Finding it can produce a larger performance improvement.
The calls column counts executions. The rows column counts the rows returned or affected across those executions. The query column contains representative SQL text. The queryid identifies the normalized statement.
Rank queries by total time
Use this query to find the statements that consumed the most execution time during the current statistics period:
SELECT queryid,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;The cast to numeric lets round use a precision argument. left(query, 80) keeps the result readable in a terminal. It may cut off the SQL text, so use queryid to identify the full statement in other tools or logs.
Read the result in this order:
- Check
total_msto find the largest cumulative costs. - Check
callsto see whether the cost comes from repetition. - Check
mean_msto understand the cost of one execution. - Check
rowsto see how much data the statement processes overall. - Read the SQL text and determine whether the workload is expected.
A high total can result from a slow query, a frequent query, or both. For example, a statement with 5,000 calls and a 20 ms mean uses roughly 100,000 ms, or 100 seconds, of execution time.
Use the ranking correctly
Statistics are cumulative. The result depends on when the counters began accumulating and which workload ran afterward. A report collected during a batch job may rank different statements than a report collected during normal web traffic.
Compare queries over a defined observation period. If a statement appears at the top, do not immediately increase configuration values or add an index. First confirm its purpose, parameters, call frequency, and execution plan. A query that returns many rows may need a different solution from a query that scans the same data repeatedly.
The ranking also excludes time spent waiting outside query execution, such as some client-side delays. Treat it as database execution evidence, not as a complete request-latency measurement.
Exercise
Query A runs 1,000 times with a mean execution time of 50 ms. Query B runs 10 times with a mean execution time of 2,000 ms. Which query has the greater cumulative execution time?
Show answer
Query A: 1,000 × 50 ms = 50,000 ms. Query B: 10 × 2,000 ms = 20,000 ms. Query A is the larger overall cost, although Query B is slower per call.