---
title: "Watch slow queries · Agent Wranglers"
url: https://agentwranglers.se/playbook/data/operations/slow-query-log
updated: 2026-10-20
licence: "All rights reserved"
---

# Watch slow queries

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Operations](https://agentwranglers.se/playbook/data/operations)
- Rule: Record queries that take longer than a set time, and fix or explain the five worst every week.
- How: 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.
- Check: Run a deliberately slow query. It appears in the slow query log or the statistics view.

Example:

```sql
-- 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;
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers data playbook: https://agentwranglers.se/playbook/data/operations/slow-query-log`.

- Previous: [Set time limits on every query](https://agentwranglers.se/playbook/data/operations/query-timeouts)
- Next: [Let routine maintenance run](https://agentwranglers.se/playbook/data/operations/maintenance)
- [Operations](https://agentwranglers.se/playbook/data/operations)
