Home › Blog › Article

Direct Queries with $wpdb: When to Use Them and How to Stay Safe

Direct Queries with $wpdb: When to Use Them and How to Stay Safe

Answer first: what to do and how to know it is right

Use a wpdb custom SQL query only when WordPress core APIs cannot express the read efficiently: complex aggregates, joins across custom tables, or reporting queries that WP_Query would turn into multiple lookups. Keep writes in core APIs unless you own the table and transaction boundary. You did it right when every variable passes through $wpdb->prepare(), the query is read-only by default, custom tables are created with dbDelta(), EXPLAIN shows an index-backed path, staging results match a known fixture, and you can disable the feature with one constant or option and roll back without touching content tables.

How it works: $wpdb internals and a minimal runnable example

$wpdb is the global instance of the wpdb class loaded from wp-includes/class-wpdb.php during wp-settings.php bootstrap. In WordPress 6.9 / 6.8-era codebases still common in 2026, it wraps mysqli (or the bundled $wpdb->dbh handle), reads DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_CHARSET, and DB_COLLATE from wp-config.php, applies $table_prefix, and exposes $wpdb->posts, $wpdb->postmeta, $wpdb->users, and $wpdb->prefix. Methods are thin: get_results() runs query() then hydrates rows into objects or arrays; get_var() returns column 0 of row 0; get_row() returns one row; query() returns affected rows or false. query() also increments $wpdb->num_queries, records $wpdb->last_query, last_error, last_result, insert_id, rows_affected, and fires the query filter when SAVEQUERIES is enabled. It does not sanitize SQL, does not add indexes, does not switch blogs, and does not invalidate caches; that last detail is why a direct UPDATE can leave wp_cache_get() stale until you call clean_post_cache(), wp_cache_flush_group(), or the appropriate clean_*_cache() function.

The safe mental model is: $wpdb is a transport and result mapper, not an ORM. WP_Query, WP_Term_Query, and get_metadata() add capability checks, cache groups, posts_* filters, and object-cache invalidation. A direct query bypasses all of that. Use it for a narrow, measured read path, keep it in a plugin file such as wp-content/plugins/acme-reporting/includes/class-acme-report-repository.php, and expose it through a shortcode, REST route, or WP-CLI command rather than sprinkling SQL in a template. Our Custom WordPress Development team typically isolates these repositories behind an interface so a later core API change can replace SQL without touching presentation code.

Minimal runnable example: safe aggregate read

Drop this into wp-content/plugins/acme-reporting/acme-reporting.php, activate it in wp-admin/plugins.php, then run wp acme-report --limit=5 from the site root. It reads published posts joined to a numeric meta value, prepares both the literal and the limit, and fails loudly instead of returning a silent empty array.

<?php
/**
 * Plugin Name: ACME Reporting (2026 demo)
 * Version: 1.0.0
 * Requires PHP: 8.1
 */

defined( 'ABSPATH' ) || exit;

final class Acme_Report_Repository {
    private wpdb $db;

    public function __construct( wpdb $db ) {
        $this->db = $db;
    }

    /** @return array<int, object> */
    public function top_by_score( string $post_type, int $limit ): array {
        $sql = $this->db->prepare(
            "SELECT p.ID, p.post_title, CAST(pm.meta_value AS UNSIGNED) AS score
             FROM {$this->db->posts} p
             INNER JOIN {$this->db->postmeta} pm
               ON pm.post_id = p.ID AND pm.meta_key = 'acme_score'
             WHERE p.post_type = %s
               AND p.post_status = 'publish'
             ORDER BY score DESC, p.ID ASC
             LIMIT %d",
            $post_type,
            $limit
        );

        $rows = $this->db->get_results( $sql );
        if ( $this->db->last_error !== '' ) {
            throw new RuntimeException( 'ACME query failed: ' . $this->db->last_error );
        }
        return $rows ?? [];
    }
}

if ( defined( 'WP_CLI' ) && WP_CLI ) {
    WP_CLI::add_command( 'acme-report', function ( $args, $assoc ) {
        $repo  = new Acme_Report_Repository( $GLOBALS['wpdb'] );
        $limit = max( 1, min( 100, (int) ( $assoc['limit'] ?? 5 ) ) );
        foreach ( $repo->top_by_score( 'post', $limit ) as $row ) {
            WP_CLI::line( sprintf( '%d | %s | %d', $row->ID, $row->post_title, $row->score ) );
        }
        WP_CLI::debug( 'Last SQL: ' . $GLOBALS['wpdb']->last_query );
    } );
}

Verify it with wp acme-report --limit=5 --debug, then wp db query "EXPLAIN SELECT p.ID FROM wp_posts p INNER JOIN wp_postmeta pm ON pm.post_id = p.ID AND pm.meta_key = 'acme_score' WHERE p.post_type = 'post' AND p.post_status = 'publish' ORDER BY p.ID LIMIT 5;". You should see type: ref on wp_postmeta using post_id plus meta_key, not ALL. Roll back by deactivating the plugin: wp plugin deactivate acme-reporting. No schema or data was changed, so there is nothing else to undo. A common pitfall here is interpolating $_GET['post_type'] into the string before prepare(); another is using %d for LIMIT but forgetting to clamp it, which lets a REST caller request LIMIT 100000000 and pin a CPU core.

Process: prepare and placeholders

  1. Write the SQL with literal table names from $wpdb->posts or $wpdb->prefix, never from request input.
  2. Replace every runtime value with %s, %d, %f, or the escaped %i identifier placeholder added in WordPress 6.2 and still the correct choice in 2026.
  3. Call $wpdb->prepare( $sql, $arg1, $arg2 ) or pass one array as the second argument; do not pre-quote values with esc_sql().
  4. For dynamic IN (...), build the placeholder list with implode( ', ', array_fill( 0, count( $ids ), '%d' ) ) and pass $ids as the argument array.
  5. Execute with get_results()/get_var(), then assert $wpdb->last_error === '' and log $wpdb->last_query with SAVEQUERIES on staging.
  6. Roll back by reverting the repository file and flushing any object cache group you warmed; prepared SQL itself never mutates data.

prepare() is not string escaping glued onto sprintf. Internally wpdb::prepare() tokenizes the query, rejects unsupported or misplaced placeholders, supports numbered (%1$s) and named-style argument arrays, calls _escape() which uses esc_sql()/$this->_real_escape() on the active mysqli connection, wraps strings in single quotes, casts %d to integer and %f to float, and since 6.2 runs %i through escape_identifier() with backtick doubling. In WordPress 6.8+ a mismatched argument count emits _doing_it_wrong() and returns an empty string rather than a half-escaped query; treat an empty return as a fatal error, not as ‘no rows’. Enable detection in wp-config.php on staging:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'SAVEQUERIES', true );
define( 'WP_DEBUG_LOG_PATH', __DIR__ . '/wp-content/debug.log' );

Get a Quote

Email + requirement + budget range — we reply with a quote within 24 hours.

Then grep the log: wp eval 'error_log( $GLOBALS["wpdb"]->last_query );' or tail -f wp-content/debug.log | grep -i doing_it_wrong. A copy-pasteable identifier example is below; it is the only safe way to let an admin choose a column name.

$allowed = [ 'acme_score', 'acme_views' ];
$column  = in_array( $input, $allowed, true ) ? $input : 'acme_score';
$sql = $wpdb->prepare(
    "SELECT post_id FROM {$wpdb->prefix}acme_metrics ORDER BY %i DESC LIMIT %d",
    $column,
    10
);

Common pitfalls: using %s for a table or column (it produces a quoted string and a syntax error), calling prepare() twice, passing null for %d, using LIKE without $wpdb->esc_like() so _ and % become wildcards, and assuming prepare() authorizes the caller. It does not; keep current_user_can( 'manage_options' ) or a REST permission_callback in front of it. The official wpdb::prepare() reference documents the placeholder set and the 6.2 identifier change. If a bad deploy reaches production, set define( 'ACME_REPORTING_DISABLED', true ), guard the repository constructor with that constant, deploy the previous release via wp plugin rollback or your CI artifact, and wp cache flush only if you cached the malformed result.

Prefer reads over writes

Default every wpdb custom SQL query to SELECT. Core write paths (wp_insert_post(), update_metadata(), wp_set_object_terms(), WP_User::set_role()) fire save_post, updated_*_meta, clean_post_cache, transition_post_status, revision creation, and object-cache deletes that a raw UPDATE wp_posts SET ... silently skips. In 2026, with persistent Redis or Memcached object caches on most agency hosting, a raw write is the fastest route to an admin screen showing old data while the database already holds the new value. It also bypasses wpdb::process_fields() format checks and, on multisite, switch_to_blog() table-prefix swapping.

When a write is genuinely required — a bulk backfill on a table you own, or a counter increment that would otherwise trigger 50,000 hooks — contain it. Use $wpdb->update( $table, $data, $where, $formats, $where_formats ) or $wpdb->query( $wpdb->prepare( ... ) ) inside a short transaction, then invalidate explicitly:

$table = $wpdb->prefix . 'acme_metrics';
$wpdb->query( 'START TRANSACTION' );
$ok = $wpdb->update(
    $table,
    [ 'acme_score' => 42, 'updated_at' => current_time( 'mysql', true ) ],
    [ 'post_id' => 123 ],
    [ '%d', '%s' ],
    [ '%d' ]
);
if ( false === $ok || $wpdb->last_error !== '' ) {
    $wpdb->query( 'ROLLBACK' );
    throw new RuntimeException( $wpdb->last_error );
}
$wpdb->query( 'COMMIT' );
clean_post_cache( 123 );
wp_cache_delete( 'acme_top_10', 'acme_reporting' );

Verify with wp db query "SELECT acme_score, updated_at FROM wp_acme_metrics WHERE post_id = 123;", then load the edit screen in a fresh incognito session and confirm the meta box reflects 42. Check $wpdb->rows_affected; MySQL returns 0 when the value was already 42, which is not an error. Roll back with the inverse UPDATE captured before the job (write it to wp-content/uploads/acme-backfills/2026-06-18.sql), or wp db import a pre-job dump taken with wp db export --add-drop-table pre-acme.sql. Never roll back by re-running the forward job with an guessed old value.

Pitfalls we see in audits: INSERT ... ON DUPLICATE KEY UPDATE on wp_postmeta without deleting the post_meta cache group; DELETE without a LIMIT or a dry-run SELECT COUNT(*); running the backfill over HTTP and hitting a 30-second proxy timeout mid-transaction; and using MyISAM tables where START TRANSACTION is a no-op. Confirm InnoDB first: wp db query "SHOW TABLE STATUS LIKE 'wp_acme_metrics'G" and read the Engine row. For long jobs use wp acme-backfill --batch=500 --sleep=200 under WP-CLI, not a cron HTTP loop. If you are reviewing a vendor’s data-migration plan, our WordPress site optimization vendor guide covers the staging and rollback gates we require before any write lands on production.

Custom tables and dbDelta

Create custom tables only when the data is not a post, term, user, or meta-shaped record: event logs, immutable analytics rollups, queue payloads, or high-cardinality join tables. Register the schema in an activation hook, call dbDelta() from wp-admin/includes/upgrade.php, and store a schema version in wp_options so upgrades run on plugin update, not only on activation. dbDelta() parses CREATE TABLE SQL, compares column names, types, and KEY definitions against DESCRIBE/SHOW INDEX, and emits ALTER TABLE statements. Its parser is famously literal: two spaces after PRIMARY KEY, the keyword KEY (not INDEX), no trailing comma on the last line, no backticks around the table name, and every field on its own line. WordPress 6.9 has not relaxed these rules.

<?php
// wp-content/plugins/acme-reporting/includes/schema.php
defined( 'ABSPATH' ) || exit;

const ACME_DB_VERSION = '1.1';

function acme_reporting_install(): void {
    global $wpdb;
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $table   = $wpdb->prefix . 'acme_metrics';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table} (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        post_id BIGINT UNSIGNED NOT NULL,
        acme_score INT UNSIGNED NOT NULL DEFAULT 0,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (id),
        UNIQUE KEY post_id (post_id),
        KEY score_updated (acme_score, updated_at)
    ) {$charset} ENGINE=InnoDB;";

    dbDelta( $sql );

    if ( $wpdb->last_error !== '' ) {
        error_log( 'ACME schema: ' . $wpdb->last_error );
    }
    update_option( 'acme_db_version', ACME_DB_VERSION );
}

register_activation_hook( ACME_REPORTING_FILE, 'acme_reporting_install' );
add_action( 'plugins_loaded', function (): void {
    if ( get_option( 'acme_db_version' ) !== ACME_DB_VERSION ) {
        acme_reporting_install();
    }
} );

Verify immediately after activation: wp db query "SHOW CREATE TABLE wp_acme_metricsG", wp option get acme_db_version, and wp db query "SHOW INDEX FROM wp_acme_metrics;". You should see post_id as UNIQUE, score_updated as a composite index, InnoDB, and the site’s charset (usually utf8mb4_unicode_520_ci or the 2026 default utf8mb4_unicode_ci variant from DB_COLLATE). Test the upgrade path by bumping ACME_DB_VERSION to 1.2, adding a column line, reloading wp-admin/, and confirming dbDelta() issued one ALTER TABLE in the debug log rather than recreating the table.

Rollback is deliberate: dbDelta() will not drop columns or indexes, so a bad 1.2 deploy is reverted by restoring the 1.1 plugin file, setting wp option update acme_db_version 1.1, and manually running wp db query "ALTER TABLE wp_acme_metrics DROP COLUMN new_column;" only after confirming no code reads it. Never DROP TABLE on uninstall without an explicit uninstall.php and an ACME_KEEP_DATA option; multisite needs get_sites() iteration because register_activation_hook runs per blog only when network-activated with $network_wide handled. Common pitfalls include forgetting $wpdb->prefix (breaks multisite), hardcoding utf8 instead of get_charset_collate(), and calling dbDelta() on every request — it runs DESCRIBE each time and adds measurable latency. The dbDelta() reference is the authoritative formatting checklist. Teams inheriting a theme that also tries to create tables should read our 2026 theme development handbook and move schema ownership into the plugin, where it survives a theme switch.

Slow queries and indexes

Slow queries and indexes

A wpdb custom SQL query becomes a production incident when it scans. Measure before and after: enable SAVEQUERIES on staging, or set MySQL 8.0 / MariaDB 11.x long_query_time = 0.2 in /etc/mysql/conf.d/90-acme.cnf and SET GLOBAL slow_query_log = 'ON';, then read /var/log/mysql/mysql-slow.log with mysqldumpslow -s t -t 10. In PHP, bracket the call with microtime( true ) and log $wpdb->num_queries plus $wpdb->last_query. Then run EXPLAIN ANALYZE (MySQL 8.0.18+) on the exact prepared SQL with representative literals.

wp db query "EXPLAIN ANALYZE SELECT p.ID, CAST(pm.meta_value AS UNSIGNED) AS score
FROM wp_posts p
INNER JOIN wp_postmeta pm ON pm.post_id = p.ID AND pm.meta_key = 'acme_score'
WHERE p.post_type = 'post' AND p.post_status = 'publish'
ORDER BY score DESC, p.ID ASC LIMIT 10;"

wp db query "SHOW INDEX FROM wp_postmeta;"
wp db query "SELECT COUNT(*) FROM wp_postmeta WHERE meta_key = 'acme_score';"

Read the plan, not the hope. type: ALL with rows in the millions means a full scan; Using filesort on CAST(meta_value AS UNSIGNED) is expected because postmeta stores LONGTEXT and no index can serve a cast. That is the strongest argument for the wp_acme_metrics.acme_score INT UNSIGNED column above: move the sortable numeric value out of meta, add KEY score_updated (acme_score, updated_at), and the plan becomes type: range / Backward index scan with rows: 10. Core’s wp_postmeta ships post_id and meta_key indexes; adding a third-party index to a core table is fragile because dbDelta() in core upgrades may not preserve it. If you must, document it in wp-content/uploads/acme-indexes.md and re-check after every WordPress minor upgrade.

Index rules that hold in 2026: put equality columns first, then range/sort columns; keep composite indexes left-prefix compatible; do not index low-cardinality booleans alone; avoid SELECT * when a covering index can satisfy the read; never wrap an indexed column in a function (DATE(updated_at)) — rewrite as updated_at >= '2026-06-01' AND updated_at < '2026-07-01'; and paginate with keyset (WHERE id < %d ORDER BY id DESC LIMIT %d) instead of OFFSET 200000. Verify the win with three numbers logged before and after: p95 wall time, rows examined from EXPLAIN ANALYZE, and slow-log entries per hour. Also verify correctness: the top-10 IDs must be identical on staging and production for the same fixture dump.

Rollback for an index change is wp db query "ALTER TABLE wp_acme_metrics DROP INDEX score_updated;" plus redeploying the previous repository version; on MySQL 8.0 this is an instant metadata change with ALGORITHM=INPLACE, LOCK=NONE, but confirm with wp db query "SHOW PROCESSLIST;" first on a busy table. Pitfalls: adding an index directly on production during peak traffic, trusting EXPLAIN without ANALYZE (estimates can be wrong after an ANALYZE TABLE gap), caching a slow result in a transient with no version key, and forgetting that $wpdb->get_results() hydrates every row into PHP objects — use ARRAY_A or get_col() for large exports. If the query still misses SLA after indexing, that is the signal to precompute the rollup in a WP-CLI job and read one row, not to add another join. More measurement patterns are collected in our technical column index.

Frequently asked questions

Is a wpdb custom SQL query faster than WP_Query by default?

No. WP_Query is slower only when it triggers multiple meta/term lookups or post-cache priming you do not need. A single well-indexed direct read can win; an unindexed join loses badly. Benchmark with SAVEQUERIES and EXPLAIN ANALYZE on a production-sized dump before replacing core APIs, and keep the core query as the fallback behind a feature flag.

Can I use esc_sql() instead of prepare() for identifiers or IN lists?

Use prepare() for values and %i for identifiers. esc_sql() only escapes a scalar and will not quote, cast, or validate placeholder counts; it also accepts arrays in a way that surprises people. For IN lists, generate matching %d/%s placeholders and pass the array to prepare(). Add esc_like() before prepare() for LIKE patterns.

How do I roll back a bad direct write without a backup?

Stop the job first, then reconstruct from $wpdb->last_query logs, the slow query log, and any binlog (mysqlbinlog --start-datetime='2026-06-18 09:00:00'). If none exist, you cannot reliably reconstruct prior values. That is why every write path must export wp db export --add-drop-table and save an inverse SQL file before COMMIT; reads need no such ceremony.

Action checklist

  • Audit every $wpdb->query() call: confirm prepare(), an allowlist for identifiers, last_error checks, and a permission callback.
  • Convert any raw write on core tables back to wp_insert_post() / update_metadata(), or add explicit cache invalidation and a pre-job dump.
  • Move schema into a plugin activation hook with dbDelta(), get_charset_collate(), $wpdb->prefix, and an acme_db_version option; verify with SHOW CREATE TABLE.
  • Run EXPLAIN ANALYZE on the exact SQL, add or fix one composite index, and record p95 time plus rows examined before and after.
  • Ship a kill switch (ACME_REPORTING_DISABLED) and a tested rollback command in the plugin README.

Need a second pair of eyes on a reporting query or a risky migration? Our engineers review $wpdb code, indexes, and rollback plans. See WordPress services or start a development engagement for a scoped audit in 2026.

References & further reading

Need WordPress Development?

Free proposal and quote within 24 hours — we serve clients worldwide.

QQ