Finding slow queries with pg_stat_statements
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
find the queries that cost the most overall.
Planned topics
- Enable the extension via
shared_preload_librariesandCREATE EXTENSION pg_stat_statements(restart required). - It aggregates by normalized query text: calls, total time, mean time, rows.
- Sort by total time, not only mean: a fast query called a million times can dominate.
- Reset with
pg_stat_statements_reset()before a test to measure cleanly. - Column names changed in PostgreSQL 13 (
total_exec_time); verify version before recording.
Draft outline details
Demonstration
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms, query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;Check your understanding
Why sort by total time?
Show answer
Frequent cheap queries can cost more in total than rare slow ones.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.