MySQL Slow Queries

What are Slow Queries in MySQL?

Slow queries are defined as database requests that exceed a certain execution time threshold. This threshold is a parameter that can be adjusted and set by database administrators or developers to align with their unique performance benchmarks.

The logging of these slow queries occurs in the slow_query log, a specialized file designated to capture details about queries that do not meet the performance criteria. This log includes critical information such as:

  • the exact SQL statement executed
  • the duration of execution
  • the precise timestamp of the query
  • the specific database schema or tables impacted

By examining the data recorded in the slow_query log, you can uncover patterns and trends in query performance, pinpointing repetitive queries that may be contributing to overall system slowdowns.

Why is Slow Queries Monitoring Important?

Monitoring slow queries is about adopting a proactive approach to system health which offers optimal performance and a superior user experience:

  • Performance Optimization – Zeroing in on slow queries allows for precise adjustments that can drastically cut down on lag and speed up database interactions. This direct approach to tweaking query execution can lead to significant reductions in wait times for data retrieval, directly translating to a smoother, more efficient operation of the database system as a whole.
  • Root Cause Analysis – Slow queries often signal deeper, systemic problems that go beyond surface-level symptoms. By focusing on these queries, administrators can trace back to inefficient schema designs, inadequate indexing, or hardware constraints that are the true culprits of performance bottlenecks. To analyze slow queries in detail and understand how they are executed, check out How to use EXPLAIN to fix slow queries in MySQL.
  • Improving the User Experience – The end goal of optimizing slow queries is to deliver a seamless interaction for users. Delays in data processing can frustrate users, affecting their perception and usage of an application. By eliminating these delays, administrators can directly contribute to a more responsive and enjoyable user experience. This is important for user retention and satisfaction. If your application uses PHP with MySQL, learn how slow queries specifically affect PHP apps and practical ways to speed them up in our dedicated guide Fix PHP MySQL Slow Queries.

How Releem Calculates Slow Queries Count

In Releem, the slow query count is automatically calculated for you – using the "slow_queries" variable retrieved from the SHOW GLOBAL STATUS command in MySQL. This variable represents the total number of slow queries recorded since your last MySQL server restart.

To help you visualize slow query metrics, Releem provides a dedicated graph within its dashboard interface. This graph displays the trend of slow queries over time, allowing admins to track performance fluctuations and identify potential anomalies or spikes.
Releem dashboard chart showing slow MySQL queries over time
Releem Dashboard, MySQL Slow Queries count

How to Show MySQL Slow Queries

You have a couple of options for viewing MySQL slow queries: manually or by using Releem SQL Query Analytics.
Using Releem SQL Query Analytics
For a more automated approach, Releem SQL Query Analytics allows you to easily view slow queries by simply clicking "Load Data" in the Query Analytics block and then sorting the queries by Execution Time.
Releem SQL Query Analytics showing SQL statements and their execution-time statistics
Identify MySQL slow queries using Releem Query Analytics
Manually Viewing the Log
If you prefer to do it manually, you can connect to your server via SSH and use the less or cat command to view the slow query log directly:
less /var/log/mysql/mysql-slow.log

This manual method gives you direct access to the log files and the flexibility to use additional Unix commands for deeper analysis.
Manually using 'mysqldumpslow'

Use mysqldumpslow to group similar statements in a slow query log and compare their execution count and query time. To list query patterns from highest to lowest total query time:

mysqldumpslow -s t -l /var/log/mysql/mysql-slow.log

Use the path to your existing slow query log. -s t sorts by total query time, and -l keeps the logged query times instead of subtracting lock time. The command reads the file; it does not execute the SQL in it. See the MySQL mysqldumpslow reference for other sorting options.

How to read a slow query log summary

Consider this example:

Count: 100  Time=1.20s (120s)  Lock=0.00s (0s)  Rows=10.0 (1000), app[app]@localhost
  SELECT id, total FROM orders WHERE customer_id = N

Count: 40  Time=1.50s (60s)  Lock=0.00s (0s)  Rows=10.0 (400), app[app]@localhost
  SELECT id, price FROM products WHERE category = 'S'

Count: 2  Time=8.00s (16s)  Lock=0.00s (0s)  Rows=1.0 (2), app[app]@localhost
  SELECT SUM(total) FROM orders WHERE created_at >= 'S'

N and 'S' replace numeric and string values, so similar statements can appear as one pattern. Read the first entry as follows:

  • Count: 100 — 100 matching executions were recorded in this file.
  • Time=1.20s (120s) — the average query time is 1.20 seconds; the displayed total is 120 seconds.
  • Lock=0.00s (0s) — the displayed average and total lock times are zero.
  • Rows=10.0 (1000) — an average of 10 rows were sent per execution, with 1,000 sent in total. These are rows sent, not rows examined.

The report query is slowest per execution at 8 seconds, but its two executions total 16 seconds. The customer-order lookup takes 1.20 seconds each time and totals 120 seconds across 100 executions. If your goal is to reduce cumulative query time, investigate the customer-order lookup first. If the report is delaying a critical user action, its individual response time may take priority.

Total query time is the sum across logged executions. Concurrent executions can overlap, so this is neither CPU time nor elapsed wall-clock time for the file.

Follow query activity in Releem

A slow log covers the statements recorded under its logging settings. For ongoing analysis, Releem collects query statistics from Performance Schema, including frequently executed queries that may not appear in the slow log.

In Query Analytics, sort by Load on Total Time to find queries with high cumulative execution time, or by Avg. Execution Time to investigate slow individual patterns. Open a query to inspect its SQL and request optimization recommendations.

See how Releem Query Analytics helps you choose what to optimize.

How to Manually Enable Slow Query Log

Releem automatically enables the slow query log during installation. However, if manual configuration is required, administrators can follow these steps:
  1. Open your MySQL server's configuration file, which is typically named my.cnf or my.ini.
  2. Scroll to the [mysqld] section within this file.
  3. To activate the logging feature insert or update the following entry:
  • slow_query_log = 'ON';
4. To specify where the logs will be stored insert or update the following entry:
  • slow_query_log_file = '/path/filename';
5. By default, when the slow query log is enabled, it logs any query that takes longer than 10 seconds to run. Here, replace "threshold" with the number of seconds you would like to define as a "slow" query:
  • long_query_time = threshold;

After making these adjustments, save your changes to the configuration file and restart the MySQL server to apply the new settings.

The slow query log can also be activated dynamically via runtime configuration by following the guidelines.

To activate the slow query log in MySQL console and execute
SET GLOBAL slow_query_log = 'ON'; at the MySQL prompt.

You can customize its behavior further by
1. adjusting the threshold for logging slow queries with
SET GLOBAL long_query_time = X; , where X is time in seconds
2. change the log file's location using
SET GLOBAL slow_query_log_file = '/path/filename'; , specifying your desired path and filename.

Discover Effortless Slow Query Management with Releem

Embrace the advanced monitoring capabilities of Releem to elevate your database management strategy. With Releem's automatic slow query logging and easy-to-read slow query graph – you're empowered to swiftly pinpoint and resolve performance bottlenecks.

While optimizing slow queries is critical, it’s equally important to consider queries that execute frequently, as they can significantly impact overall server load even if they run quickly. Balancing your optimization efforts between slow queries and top-executed queries ensures the best performance results.

To learn how to analyze and improve both slow and frequently run queries, check out our detailed guide Query Optimization in MySQL: Optimizing Top Queries vs. Slow Queries.

The General Query Log is just one piece of the puzzle. To understand how it interacts with Error, Slow, and Binary logs, read our Complete Guide to MySQL Logs.

To learn how to actually rewrite and optimize count queries and other slow MySQL commands, check our performance guide.