Sub topic 2
Finding the queries that cost the most overall
This chapter assumes you have already enabled pgstatstatements, can use SELECT with ORDER BY, LIMIT, and aggregate expressions, and have access to psql. You should also know roughly what a query plan is.
Finding the queries that cost the most overall
pgstatstatements keeps one row per normalized query and adds up every execution of it. The total_exec_time column holds the total time, in milliseconds, spent running that query. Sorting by this column shows which statements use the most server time overall.
SELECT queryid,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Slow per call versus expensive in aggregate
A query can rank high because it runs often, or because each run is slow. Mean time separates the two cases. A minimum call count filters out one-off statements.
SELECT queryid,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(max_exec_time::numeric, 2) AS max_ms,
left(query, 80) AS query
FROM pg_stat_statements
WHERE calls >= 50
ORDER BY mean_exec_time DESC
LIMIT 10;A high total with a low mean usually means a frequent, cheap query. A high mean with few calls is an outlier that deserves a look.
Spotting I/O-heavy queries with buffer counters
shared_blks_hit counts blocks found in shared buffers, which is memory. shared_blks_read counts blocks fetched from outside them. A high read count with a low hit percentage points to I/O-bound work.
SELECT queryid,
calls,
shared_blks_hit,
shared_blks_read,
round(100.0 * shared_blks_hit
/ nullif(shared_blks_hit + shared_blks_read, 0), 1) AS hit_pct,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 10;Taking a suspect query to EXPLAIN (ANALYZE, BUFFERS)
pgstatstatements shows that a query is expensive, but not why. Copy the suspect query, replace any placeholders with realistic values, and run it under EXPLAIN:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;ANALYZE executes the statement, so wrap data-changing statements in a transaction you roll back. BUFFERS reports hit and read counts for this single run, which you can compare with the averages from the statistics.
Exercise
Query A has calls = 2 and meanms = 900. Query B has calls = 500000 and meanms = 1. Which should you check first, and why?
Show answer
Check Query B first. Its total time is about 500000 ms, or roughly 500 seconds, while Query A totals 1800 ms. Query A is still worth a look because its high mean suggests an outlier, but Query B has far more total load.