AI Hints
Home›PostgreSQL Tutorial›Finding and Fixing Slow Queries
PostgreSQL · Lesson 91 of 120

pg_stat_statements

Find the slow queries.

⏱ 2 min read▶ Video at 1:21:56🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Which queries use the most time in your database? Guessing doesn't work. The pg stat statements extension records every query shape, how often it ran, and how long it took.

  • Which are slow?
  • Don't guess
  • Measure

Top queries by total time

We create the extension, reset it, and run a few queries. Then we ask for the top queries by total time. Similar queries are grouped, with values replaced by dollar signs. Run it. The heaviest query shapes, with call counts.

query.sqlsql
CREATE EXTENSION pg_stat_statements;
SELECT pg_stat_statements_reset() IS NOT NULL AS reset;

SELECT count(*) FROM orders WHERE customer_id = 7 \g /dev/null
SELECT count(*) FROM orders WHERE customer_id = 8 \g /dev/null
SELECT title FROM books WHERE book_id = 3 \g /dev/null

SELECT calls, round(total_exec_time::numeric, 3) AS ms, left(query, 50) AS query
FROM pg_stat_statements
WHERE query LIKE 'SELECT%FROM orders%' OR query LIKE 'SELECT title%'
ORDER BY total_exec_time DESC;
Output
CREATE EXTENSION
 reset
-------
 t
(1 row)

 calls |  ms   |                       query
-------+-------+----------------------------------------------------
     2 | 0.096 | SELECT count(*) FROM orders WHERE customer_id = $1
     1 | 0.008 | SELECT title FROM books WHERE book_id = $1
(2 rows)

What to look at

Total time shows which queries cost the most overall. Mean time shows which are slow each time. Calls shows how often. Fix the top few, and you'll often fix most of the load.

keyvalue
total_exec_timeoverall cost
mean_exec_timeslow each time
callshow often
rowsrows returned

Summary

Pg stat statements shows which query shapes use the most time. Next, a workflow for fixing them.

Key takeaways
  • pg_stat_statements
  • total time
  • calls
Next up: A Slow Query Workflow — measure, explain, fix