Performance and monitoring

Save WordPress SQL queries to a log

Reviewed on 5 min read WordPress database logs

Saving the SQL queries WordPress makes lets you see which ones take longest, which ones are repeated and which plugin runs them, so you know what to optimise.

Before touching any code, consider two simpler alternatives:

  • PHP X-Ray, included in our plans: it analyses a URL and shows you each query with its time, the file and the plugin that runs it. You do not need to modify WordPress.
  • Query Monitor: a plugin that, while you browse as an administrator, shows the page's queries, the slow ones and the duplicates in the top bar, grouped by plugin.

If you need a log of the queries from many visits (for example, to track down slowness that only happens now and then), follow these steps.

Step 1: enable SAVEQUERIES

Edit wp-config.php and add this line before /* That's all, stop editing! Happy publishing. */:

define('SAVEQUERIES', true);

With this, WordPress keeps every query of each request in memory, with its duration and the function that ran it. It increases memory usage, so remove it as soon as you have finished.

Step 2: write the queries to a file

Create the file wp-content/mu-plugins/sql-logger.php (create the mu-plugins folder if it does not exist). Files in that folder load on their own, without being activated, and are not lost when you update the theme, as would happen in functions.php.

<?php
/**
 * Temporary SQL query log. Delete it when you have finished.
 */

// File outside public_html so it cannot be downloaded from the web.
// Replace "tuusuario" with your cPanel username.
const SQL_LOGGER_FILE = '/home/tuusuario/sql_log.txt';

// Only queries that take longer than this many seconds are logged.
// Set it to 0 to log them all.
const SQL_LOGGER_MIN_TIME = 0.05;

add_action('shutdown', function () {
    global $wpdb;

    if (! defined('SAVEQUERIES') || ! SAVEQUERIES || empty($wpdb->queries)) {
        return;
    }

    $lines = [];
    foreach ($wpdb->queries as [$sql, $time, $caller]) {
        if ($time >= SQL_LOGGER_MIN_TIME) {
            $lines[] = sprintf("%.4f s | %s\n  %s\n", $time, $caller, $sql);
        }
    }

    if ($lines) {
        $header = sprintf("==== %s %s (%d consultas en total)\n",
            date('Y-m-d H:i:s'), $_SERVER['REQUEST_URI'] ?? 'cli', count($wpdb->queries));
        file_put_contents(SQL_LOGGER_FILE, $header . implode('', $lines) . "\n", FILE_APPEND | LOCK_EX);
    }
});

Each visit adds the date, the URL and the queries that exceed the minimum time to the file, with their duration and the chain of functions that ran them (that is where you will see the name of the plugin or theme).

Save the file outside public_html, as in the example: queries can contain email addresses, customer data or hashed passwords, and anyone could download a file inside the website. Your cPanel username appears in the File Manager path (/home/tuusuario).

Step 3: review the log

Browse the slow pages (or wait for visits to come in) and open sql_log.txt from cPanel's File Manager. Look for:

  • Queries that take a long time: these are the ones worth optimising with an index or by reviewing the plugin that runs them.
  • Lots of identical small queries in the same visit: this is usually a plugin running queries inside a loop.
  • The responsible plugin: it appears in the chain of functions for each query.

If you have a page cache enabled, visits served from the cache do not run WordPress and will not appear in the log: test while logged in or disable the cache while you measure.

To understand and fix what you find, there are guides on slow queries with SQL_CALC_FOUND_ROWS, slowness caused by LEFT JOIN and the wp_options table.

When you have finished

  1. Delete wp-content/mu-plugins/sql-logger.php.
  2. Remove the line define('SAVEQUERIES', true); from wp-config.php.
  3. Delete sql_log.txt: it grows with every visit and contains data from the website.

You may also find useful

Something wrong or out of date? Tell us and we will review it.