DAT-38Recommended
Watch slow queries
Record queries that take longer than a set time, and fix or explain the five worst every week.
How to do it
In PostgreSQL, load pg_stat_statements through shared_preload_libraries, run CREATE EXTENSION pg_stat_statements, and set log_min_duration_statement, such as 500 ms. In MySQL, use the slow query log. Review the top queries by total time each week, because a fast query run a million times can cost more than one slow one. Request durations from Measure rate, errors and duration show which routes the slow queries hurt.
Examples
SQL example
-- PostgreSQL: the 10 queries that cost the most time in total
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time) AS mean_ms, query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
How to check
Run a deliberately slow query. It appears in the slow query log or the statistics view.
Sources
Related rules
- DAT-10 Read the query plan in Data and databases
- OPS-12 Measure rate, errors and duration in Operations and observability
- SCL-11 Cache what is read often and costly to build in Scaling
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/operations/slow-query-log">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.