Monitoring

Slow database queries on MySQL or MariaDB: find them and fix them

In this article10 sections

A slow website very often has a slow database behind it. The symptoms are familiar: pages that take two or three seconds to start loading, the mysqld or mariadbd process sitting at the top of top, errors about too many connections, and the same pages being fast after a restart and slow again an hour later. People respond by buying a bigger server, which helps for a while and then stops helping, because the real problem is a handful of queries that do far more work than they should.

This guide shows how to find those queries, how to read what the database says about them, how to fix the common causes, and which server settings are worth touching. The order matters: measure first, change one thing at a time, and keep a backup before you alter any table.

First: is it the database at all?

Look at what the database is doing right now:

sudo mysqladmin processlist status
sudo mysql -e "SHOW FULL PROCESSLIST;"
top -b -n 1 | head -15

If Time values in the process list are large and the same query appears many times, the database is the bottleneck. If the list is mostly Sleep, the database is fine and the time is going elsewhere (PHP, the network, or an external API call). The State column tells you if queries are waiting on locks (“Waiting for table metadata lock”) rather than working.

Step 1: Turn on the slow query log

The slow query log records every query that takes longer than a threshold. It is the single most useful tool. You can enable it without a restart:

sudo mysql -e "SET GLOBAL slow_query_log = 1; SET GLOBAL long_query_time = 1;"
sudo mysql -e "SHOW VARIABLES LIKE 'slow_query_log_file';"

That records anything slower than one second, and the second command tells you where the file is (commonly /var/log/mysql/mysql-slow.log, or a file named after the host in the data directory). These settings reset on restart; to keep them, add them to the server configuration under [mysqld] (for example in /etc/mysql/conf.d/slow.cnf):

slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1

Let it collect for a day of normal traffic, including your busiest hours. Resist turning on log_queries_not_using_indexes at first: it produces a great deal of noise.

Step 2: Summarise the log

Do not read the raw file; summarise it. MySQL ships a basic tool:

sudo mysqldumpslow -s t -t 10 /var/log/mysql/mysql-slow.log

This lists the ten queries that took the most total time, with values replaced by N and 'S' so identical queries group together. For a better report, the Percona Toolkit’s pt-query-digest ranks queries by their share of total time, which is the number that matters:

sudo pt-query-digest /var/log/mysql/mysql-slow.log | head -60

Focus on the top three. A query that takes 0.2 seconds and runs 50,000 times costs far more than one that takes five seconds and runs twice.

Step 3: Read EXPLAIN

Take one slow query and ask the database how it executes it, by putting EXPLAIN in front:

EXPLAIN SELECT * FROM wp_postmeta WHERE meta_key = '_price' AND meta_value > 100;

Read these columns:

  • type: ALL means a full table scan, reading every row. That is the usual culprit on big tables. Better values are ref, range, eq_ref and const.
  • key: the index actually used. NULL means none.
  • rows: how many rows the database expects to examine. A large number for a query that returns few rows is a warning.
  • Extra: Using filesort and Using temporary indicate sorting or temporary tables that may spill to disk; Using index is good.

MySQL 8.0.18 and later also have EXPLAIN ANALYZE, which actually runs the query and shows real timings. MariaDB has the ANALYZE statement for the same purpose. Run those on a copy or off-peak, because they execute the query.

Step 4: Fix it with the right index

The most common fix is an index that matches how the query filters and sorts. Check what exists:

SHOW INDEX FROM wp_postmeta;

If a query filters on meta_key and sorts by post_id, an index on (meta_key, post_id) can turn a full scan into a lookup. Some rules of thumb:

  • Column order in a multi-column index matters. Put the columns used for equality tests first, then range or sort columns.
  • An index helps reads and slows writes a little, and uses space. Do not add one for every query; add the ones the log proves you need.
  • Functions on the column defeat the index. WHERE YEAR(created) = 2026 cannot use an index on created; WHERE created >= '2026-01-01' AND created < '2027-01-01' can.
  • A leading wildcard (LIKE '%word') cannot use an index.

Always back up the database before changing a table (mysqldump --single-transaction dbname > backup.sql), and add indexes to a large table in a quiet period. InnoDB can usually add an index while the table stays readable, but the operation still uses disk and time, and the exact behaviour depends on your version. Test it on a copy first.

WordPress specifics

WordPress has two well-known database problems.

Autoloaded options. Every page load reads all rows in wp_options that are flagged to load automatically. Plugins that leave large data there (caches, logs, old settings) make every request slower. Measure it:

SELECT ROUND(SUM(LENGTH(option_value))/1024) AS autoload_kb FROM wp_options WHERE autoload = 'yes';
SELECT option_name, ROUND(LENGTH(option_value)/1024) AS kb FROM wp_options WHERE autoload = 'yes' ORDER BY LENGTH(option_value) DESC LIMIT 10;

Newer WordPress versions use more autoload values than yes, so also look at SELECT DISTINCT autoload FROM wp_options;. A few hundred kilobytes is normal; several megabytes is a problem. The largest rows usually show which plugin put them there. Change only what you understand, and deactivating or removing that plugin properly is better than deleting rows by hand.

wp_postmeta and queries from plugins. Custom fields, page builders and shop plugins query wp_postmeta heavily. A persistent object cache (Redis or Memcached) removes many repeated queries, and your slow query log will show which plugin issues the expensive ones. A plugin that runs a slow query on every page is a candidate for replacement.

Step 5: The settings worth checking

Tuning is the last step, not the first. Three settings do most of the work:

  • innodb_buffer_pool_size: the memory InnoDB uses to cache data and indexes. On a server that runs only the database, a large share of RAM (often 50 to 70 percent) is typical. On a small server that also runs the web server and PHP, set it lower, and leave memory for them. If it is too small, the database reads from disk constantly. See the SiteHarbour guides to tuning MariaDB for a high-performance server and for low-RAM WordPress hosting.
  • max_connections: do not raise it as a cure for “too many connections”. Each connection uses memory, and the real cause is usually slow queries holding connections open. Fix the queries first.
  • Temporary tables and sort buffers: raise only if the slow log shows disk temporary tables for queries you cannot rewrite.

Change one setting at a time, restart or set it dynamically, and compare the slow log before and after.

Step 6: Fix the application side

Some slow queries cannot be fixed in the database because the application asks for too much:

  • The same query repeated hundreds of times per page (the “N+1” pattern): ask the plugin or framework author, or cache the results.
  • No pagination: loading thousands of rows to show twenty.
  • Searching with LIKE '%term%' on large tables: a search index (a plugin using full-text search, or Elasticsearch) is the right tool.
  • Cron jobs and imports running at peak hours.

Keeping it healthy

  • Leave the slow log on with a threshold of one second, and review the top queries monthly.
  • Alert on connections and CPU (see monitoring a small server).
  • Watch table sizes and disk, and rotate or expire binary logs (see what is eating your disk).
  • Back up and test restores, because all this tuning assumes the data is safe.

When it is worth getting help

If the database is the bottleneck and the site earns money, an hour of expert profiling often saves months of paying for bigger servers. I read slow query logs, EXPLAIN output and server settings, find the queries that matter and fix them (indexes, configuration, application changes), and show you the before and after.

You can see my profile on Upwork and describe the symptoms, or read about monitoring and upkeep.