Debug WordPress SQL Queries

There are several ways to investigate problems with WordPress SQL queries. The most important ways are described below.

Enable Debugging

First step is to enable the debug mode. To enable the debug mode, adjust the wp-config.php as follows:

define( 'WP_DEBUG', true ); // enables debugging
define( 'WP_DEBUG_LOG', true ); // write debug informations to /wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false ); // do not display debug informations

Attention: Under all circumstances you should avoid setting WP_DEBUG_DISPLAY to true in production environments. Debugging information may contain sensitive data that is not intended for the eyes of visitors! After you finished debugging, disable the debug mode completely and delete the debug.log, because the log file may contain sensitive information!

Query Debugging

$wpdb provides two methods to enable or disable query debugging:

global $wpdb;
$wpdb->show_errors(); // shows error messages
// or
$wpdb->hide_errors(); // hide error messages


Caution: $wpdb->show_errors() displays error messages even if WP_DEBUG is set to false! For this reason, a check for WP_DEBUG should always be included:

global $wpdb;

if ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) {

To output any error you can use the following command:


This command checks whether an error occurred in the last query and displays it.

It is also important to know that $wpdb->insert() returns false if an error occurred:

global $wpdb;
if ( !$wpdb->insert() ) {
    echo "there was an error";

All Queries

To get / see all queries executed by WordPress, SAVEQUERIES must be set to true in wp-config.php

define( 'SAVEQUERIES', true );

Now all queries are kept in the array $wpdb->queries. The following code helps to output all queries:

if ( current_user_can( 'administrator' ) ) {
    global $wpdb;
    echo "";
    print_r( $wpdb->queries );
    echo "";

Common Problem

What if no error message appears, but an entry is still not inserted? A common problem is that the data being inserted contains invalid characters or the data is simply too long. Assuming a field is of type varchar(50) and a string of 60 characters is to be inserted, no error message will appear! For this reason, always check which data is to be inserted and whether the data can be inserted in this way.


One more information when using WordPress Multisite. For query debugging to work DIEONDBERROR must be activated in the wp-config.php:

define( 'DIEONDBERROR', true );