A slow query is a database statement that takes longer to execute than an expected threshold, for example the long_query_time setting in MySQL or log_min_duration_statement in PostgreSQL. Slow queries are usually caused by missing or unsuitable indexes, large scans, lock contention or inefficient access patterns in the application. Because many requests depend on the database, a single slow query can raise the latency and error rate of several services at once.
What is a slow query?
A slow query is a database statement whose execution time exceeds what is acceptable for its purpose. There is no universal limit: a reporting query may run for minutes, while a lookup in the checkout path should finish in a few milliseconds. In practice, teams define a threshold per database or per workload and treat everything above it as slow.
Slow queries matter because the database is shared. A statement that holds locks, saturates disk I/O or occupies connections for too long does not only delay its own request. It can block other transactions, exhaust the connection pool of the application and raise the tail latency of services that never run the slow statement themselves.
Common causes of slow queries
- Missing or unsuitable indexes: the database has to scan a whole table instead of reading a few rows. Composite indexes in the wrong column order or functions applied to indexed columns prevent the index from being used.
- Large result sets and scans: queries without selective filters,
SELECT *on wide tables or missing pagination read and transfer far more data than needed. - Lock contention: long transactions hold row or table locks, and other statements wait. In the worst case a deadlock forces the database to abort one of the transactions.
- Stale statistics and plan changes: the query planner relies on table statistics. Outdated statistics or a changed data distribution can lead to a worse execution plan for a query that used to be fast.
- Inefficient access patterns: the N+1 query problem produces many small queries that are fast individually but slow in sum.
- Resource saturation: CPU, memory, disk I/O or replication load on the database server slows down all statements, not just a single one.
Finding slow queries in the database
Most relational databases can record statements above a threshold. In MySQL the slow query log is enabled with two settings, shown here with a threshold of one second as an illustration:
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
In PostgreSQL the parameter log_min_duration_statement writes statements above a duration to the server log. For an aggregated view, the extension pg_stat_statements collects execution counts and times per normalized statement:
SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Sorting by total time instead of mean time is often more useful: a query that takes 5 ms but runs millions of times per hour can cost more than a rare query that takes several seconds.
Analyzing a slow query with EXPLAIN
Once a slow query is identified, the execution plan shows why it is slow. EXPLAIN displays the plan the optimizer intends to use, and EXPLAIN ANALYZE in PostgreSQL, or EXPLAIN ANALYZE in MySQL 8.0.18 and later, runs the statement and reports actual row counts and timings per step. Typical findings are sequential scans on large tables, nested loops over many rows, large differences between estimated and actual rows, and sorts that spill to disk. Because EXPLAIN ANALYZE executes the statement, run it with care on statements that modify data.
The application view: slow queries in traces
Database logs show which statements are slow, but not which endpoint, user action or deployment caused them. Traces close this gap. OpenTelemetry instrumentation records database calls as client spans with attributes such as the database system and the statement text, so a slow request can be followed from the HTTP endpoint down to the query. This also reveals patterns that are invisible in the database alone, such as the same query executed hundreds of times within a single request, or time spent waiting for a free connection before the query even starts.
Monitoring and alerting on slow queries
- Track query latency as percentiles per normalized statement, not only as an average, because averages hide the slow outliers that users notice.
- Watch the trend: a query that becomes gradually slower as a table grows is a capacity problem long before it becomes an incident.
- Correlate with deployments: a query that suddenly becomes slow right after a release often points to a changed access pattern or a missing index for new code.
- Combine query metrics with lock waits, connection usage and server resources to distinguish a single bad query from a generally overloaded database.
Our article on database monitoring and slow queries in MySQL and PostgreSQL goes deeper into metrics and tuning.
How Obseria helps
Obseria Database Monitoring shows slow queries, connections, locks and replication for PostgreSQL, MySQL and other databases, linked to the traces of the services that issue them. With the PostgreSQL and MySQL integrations, you can move from a slow endpoint to the responsible statement and back. Alerts can be defined on query latency and trends, and Obseria Intelligence helps correlate a slowdown with deployments and infrastructure changes.