Help more people learn by sharing this post!

MySQL – Slow query analysis

Ever wonder why your application is slow? Then there is a good chance you got slow queries! In this post, you will learn how to enable the slow query log and analyze it to find how what you need to optimize.

The mysql slow log

MySQL (and probably other databases as well) have this feature that allows you to log queries that take too long to execute. It’s disabled by default (in version 5.6) and to enable it we will need to edit the configuration file. Normally this file is located at /etc/mysql/my.cnf

We will add the following lines inside the [mysqld] block:

Make sure that /var/log/mysql exist, if not create it and change permissions so mysql can write to it. Next you will need to restart the server for the changes to take effect, if the server doesn’t come up you may have a syntax error in your config file.

If this is a dev environment you will need to stress you app a bit to generate some data and then you can jump to the next section.

Log analysis

You could just open the log directly, but it’s not the most pretty thing to look at, so we are going to use a tool from the Percona toolkit. You can either download the full toolkit or just the specific tool that you need.

In this case, the tool we need is pt-query-digest which will parse the query log and show us some statistics and detailed info about our queries.

mysql slow

The top queries in the list are probably a good target for optimization.

But what if you can’t change your MySQL server settings? Well this tool has you covered! It has 2 other ways it can read queries from: tcpdump output and the ‘show process’ command.

To use the tcpdump output option you need to do this:

And for the process option:

If you would like to learn more about MySQL administration and performance I would recommend checking out Percona’s site which has plenty of free resources to help you.

I hope you found that useful, please leave a comment if you have any questions or anything interesting to add.