Slow MySQL query is a common cause of the application bottleneck. Slow queries are often discovered when a large dataset is added, which means they often happen in a production environment.
In this tutorial, we will learn how to debug slow MySQL queries.
mysql -u root -p
use my_database
SET GLOBAL slow_query_log = 'ON’;
SET GLOBAL long_query_time = X;
show variables like '%slow%’;
The command above would show the log file path as well.
SELECT SLEEP(X);
The log file should show a log belongs to the query above.
Now we have successfully enabled MySQL slow query log and we can now investigate and debug which query is causing the problem.
When we have identified the problem, always remember to turn off the slow query log since it would add additional time to each query we run.
SET GLOBAL slow_query_log = ‘OFF’;
show variables like '%slow%’;
We also introduce some useful MySQL commands you may find useful.
select SQL_NO_CACHE * from mytable where 1 limit 1;
We hope you find this tutorial helpful.