Skip to main content
Documents
Clauses StatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL SHOW SLOW LOGS for Slow Queries Performance Optimization

MySQL's slow query log feature is a performance optimization tool that records SQL queries taking longer than a specified duration to execute. It helps database administrators identify and optimize inefficient queries to improve overall database performance.

Usage

The slow query log is used to monitor and record long-running queries that can negatively impact database performance. It is especially useful in identifying bottlenecks and optimizing query execution times.

SHOW VARIABLES LIKE 'slow_query_log';

This syntax checks whether the slow query log is enabled on your MySQL server.

Examples

1. Enabling Slow Query Log

SET GLOBAL slow_query_log = 'ON';

This command enables the slow query log, allowing MySQL to start logging queries that exceed the configured time threshold.

2. Disabling Slow Query Log

SET GLOBAL slow_query_log = 'OFF';

Use this command to disable the slow query log when it's no longer needed.

3. Checking Slow Query Log File Location

SHOW VARIABLES LIKE 'slow_query_log_file';

This query retrieves the path of the file where slow queries are logged, helping administrators locate and analyze the log file. By default, the slow query log file is located in the data directory with the name hostname-slow.log.

4. Setting Long Query Time

SET GLOBAL long_query_time = 2;

This command sets the threshold for slow queries to 2 seconds, meaning any query running longer than this duration will be logged.

5. Viewing Slow Query Log Contents

To view the contents of the slow query log file, you can use command-line tools such as cat or tail:

cat /path/to/slow_query_log_file
tail -n 100 /path/to/slow_query_log_file

These commands allow you to read or view the last 100 lines of the slow query log file to analyze query performance.

Tips and Best Practices

  • Regularly review logs. Make it a habit to periodically check slow query logs for performance optimization.
  • Use sensible thresholds. Set long_query_time to a value that reflects your application's performance requirements without logging too many queries.
  • Optimize identified queries. Focus on optimizing queries found in the slow log by examining execution plans and indexing strategies.
  • Rotate log files. Regularly rotate and archive slow query logs to prevent them from growing too large and impacting server performance.
  • Monitor impact. After optimizing queries, monitor the system's performance to ensure improvements are achieved.
  • Understand performance overhead. Be aware that enabling the slow query log can introduce some performance overhead, especially in high-traffic environments. Use it judiciously and disable it when not actively monitoring slow queries.

SQL Upskilling for Beginners

Gain the SQL skills to interact with and query your data.
Start Learning for Free