Enable the MySQL slow query log and analyze WordPress database performance
Without logging, slow queries are invisible: the site is slow, but it is not clear which query, from which plugin, is to blame. MySQL’s slow query log records every statement that runs longer than a threshold. It can be enabled on a live server without a restart, and with a threshold of about half a second its overhead is negligible.
Problem: The database makes the site slow, and there is no systematic way to find out which queries are responsible.
Solution: Enable the slow query log with a threshold of 0.5 seconds, collect the queries for some time, and aggregate them with mysqldumpslow or pt-query-digest.
Enable it
At runtime, without a restart (needs the SUPER or SYSTEM_VARIABLES_ADMIN privilege):
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log'; SET GLOBAL long_query_time = 0.5; SET GLOBAL slow_query_log = ON;
long_query_time applies to new connections. To keep the settings after a restart, add them to the server configuration (/etc/mysql/mysql.conf.d/mysqld.cnf on Ubuntu, /etc/my.cnf on many other systems):
[mysqld] slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow.log long_query_time = 0.5
Start with 0.5 seconds and lower it to 0.2–0.1 when the obvious problems are fixed.
log_queries_not_using_indexes = 1 also logs fast queries that scan a whole table, which become slow when the table grows. On WordPress it can flood the log with harmless queries on small tables, so enable it for a short time and together with min_examined_row_limit = 1000.
Analyze
mysqldumpslow comes with MySQL and groups similar queries:
# the 20 queries with the largest total time mysqldumpslow -s t -t 20 /var/log/mysql/slow.log # the most frequent ones mysqldumpslow -s c -t 20 /var/log/mysql/slow.log
pt-query-digest from Percona Toolkit gives a more detailed report: percentiles, the share of the total load and an example of every query.
pt-query-digest /var/log/mysql/slow.log > slow-report.txt
Most WordPress queries can be recognized by their tables and conditions: wp_options with autoload, wp_postmeta with meta_value, a plugin’s own tables. The next step for each slow query is EXPLAIN and the right index.
Rotate the log
So the log does not grow forever, /etc/logrotate.d/mysql-slow:
/var/log/mysql/slow.log {
weekly
rotate 4
missingok
notifempty
compress
delaycompress
postrotate
mysqladmin flush-logs slow
endscript
}
mysqladmin needs credentials; on Debian/Ubuntu root usually connects through the socket without a password, otherwise put them into /root/.my.cnf.
NOTE: Compare the times in the log with the access log and traffic: a query that is slow only at night may be a cron job or a backup, not a visitor problem. And on shared hosting, where you cannot change MySQL settings, Query Monitor shows the slow queries of each page directly in WordPress.