The slow query log captures SQL statements that exceed a time threshold, helping you detect and optimize poorly performing queries.
The slow query log records statements whose execution time exceeds long_query_time
or that skip indexes when log_queries_not_using_indexes
is enabled. Reading this file reveals which queries add latency to your application.
Activate logging at runtime with SET GLOBAL slow_query_log = ON;
and define the file path, threshold, and other options. Use mysqladmin flush-logs
to rotate logs without restarting.
long_query_time
(seconds) controls the cutoff. Lower it during troubleshooting (e.g., 0.5 s) and raise it once critical queries are fixed. Toggle log_queries_not_using_indexes
to capture table scans.
Run mysqldumpslow -s t /var/log/mysql/slow.log
to sort by execution time. For live sessions, query performance_schema.events_statements_summary_by_digest
to aggregate metrics without reading files.
Copy the query into EXPLAIN ANALYZE
(MySQL 8.0+). The plan highlights full scans, missing indexes, and row counts. Compare the plan before and after adding indexes or rewriting joins.
Focus on foreign keys and filter columns. Example: an index on OrderItems(order_id)
speeds joins with Orders
. Composite indexes often outperform multiple single-column indexes.
Keep the slow query log enabled in staging. Regularly review performance_schema
digests, archive old log files, and automate index suggestions with tools like pt-query-digest.
Restarting MySQL to change log settings causes downtime—use SET GLOBAL
instead. Forgetting to raise long_query_time
after testing floods disks with trivial queries.
Yes, the overhead is minimal when long_query_time is ≥1 s. Rotate and compress logs to control disk usage.
MySQL 8.0+ stores the same data in performance_schema tables. Query events_statements_summary_by_digest
for real-time aggregation.
No. EXPLAIN ANALYZE executes the statement but discards the result set, making it safe for SELECT queries in read-only sessions.