Plugins Plugin hub Backup SEO Caching Security Forms WooCommerce Images Best backup plugins
Hosting Hosting directory Shared hosting Managed WordPress Cloud hosting VPS hosting By reader location Hosting finder
Themes & builders Compare Rank Math vs Yoast
Tools All tools Hosting finder Plugin stack builder Cost calculator Salt generator Theme detector Who is hosting this? Speed test Headline analyzer robots.txt generator Redirect generator Uptime calculator Blog name generator
Blog Best backup plugins Deals
Guides All guides Speed up WordPress Choose hosting Back up WordPress
How we test

Developer · Guide

How to Query WordPress Database (Step by Step)

How to Query WordPress Database (Step by Step)

Short answer

To query the WordPress database, use WP_Query for posts, or the global $wpdb object with $wpdb->prepare() and methods like get_results() for custom SQL. For one-off checks, run SQL in phpMyAdmin's SQL tab or with the wp db query command in WP-CLI, after taking a backup.

Key takeaways

  • Use WP_Query and helper functions for posts, users and options where possible.
  • Use $wpdb with prepare() for custom SQL to prevent SQL injection.
  • Use $wpdb table properties so the table prefix is always correct.
  • phpMyAdmin and WP-CLI suit one-off checks and scripts.
  • Back up before any query that changes data.

How do you query the WordPress database?

Use the global $wpdb object in PHP with $wpdb->prepare() for safe custom queries, use WP_Query for posts, or run SQL directly in phpMyAdmin or with WP-CLI's wp db query.

WordPress stores everything in a MySQL or MariaDB database: posts, pages, users, settings, comments and plugin data. You can read and change that data in several ways, and the right one depends on what you need.

MethodBest forSkill level
WP_Query and helper functionsFetching posts, pages and custom post typesBeginner to intermediate
$wpdb in PHPCustom tables, reports, complex SQLIntermediate
phpMyAdmin SQL tabOne-off checks and fixesIntermediate
WP-CLI wp db queryScripts and server workIntermediate to advanced
Query Monitor pluginSeeing which queries a page runsBeginner

Always back up the database before running anything that changes data. Our guide on backing up a WordPress database covers the options.

Should you use WP_Query instead of raw SQL?

Yes, for posts, pages and custom post types, WP_Query is usually better because it handles caching, permissions, filters and table names for you.

WP_Query builds the SQL behind the scenes. It respects post status, works with caching plugins and lets other plugins adjust queries through filters.

A simple example that gets the five latest posts in a category:

$query = new WP_Query( array(
  'category_name'  => 'news',
  'posts_per_page' => 5,
) );
while ( $query->have_posts() ) {
  $query->the_post();
  echo '<h2>' . esc_html( get_the_title() ) . '</h2>';
}
wp_reset_postdata();

Our guide on how to use WP_Query covers its arguments in depth.

For custom field filters, see fixing a meta query.

Similar helper functions exist for other data, such as get_users() for users, get_comments() for comments and get_option() for settings. Reach for raw SQL only when these cannot do the job.

What tables does WordPress use?

A standard install has about a dozen core tables, such as wp_posts, wp_postmeta, wp_users, wp_usermeta, wp_options and wp_comments, all starting with your table prefix.

The prefix defaults to wp_ but many sites change it. It is set in wp-config.php as $table_prefix. In code, never hard-code it.

Key tables:

  • wp_posts holds posts, pages, menu items, attachments and custom post types
  • wp_postmeta holds custom fields for those posts
  • wp_users and wp_usermeta hold accounts and user settings
  • wp_options holds site settings and plugin options
  • wp_terms, wp_term_taxonomy and wp_term_relationships hold categories and tags
  • wp_comments and wp_commentmeta hold comments

Plugins often add their own tables. WooCommerce, for example, adds order and lookup tables.

The database engine matters a little too. Most hosts run MySQL or MariaDB, and standard SQL works on both. Our comparison of MySQL vs MariaDB for WordPress covers the small differences.

To see all tables on your site, run SHOW TABLES in phpMyAdmin or WP-CLI. Tables from plugins you removed long ago often remain, and they are worth reviewing before any cleanup.

How do you run a query with $wpdb?

Declare global $wpdb, build your SQL with $wpdb->prepare() for any variable values, then call a method such as get_results(), get_var(), get_row() or get_col().

The wpdb class reference documents every method. The common read methods are:

  • get_results() returns many rows
  • get_row() returns one row
  • get_var() returns a single value
  • get_col() returns one column as a list

Example that counts published posts by one author:

global $wpdb;
$count = $wpdb->get_var(
  $wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->posts}
     WHERE post_author = %d
     AND post_status = 'publish'
     AND post_type = 'post'",
    $author_id
  )
);

Example that lists the ten most recent comments:

global $wpdb;
$rows = $wpdb->get_results(
  "SELECT comment_author, comment_date
   FROM {$wpdb->comments}
   ORDER BY comment_date DESC
   LIMIT 10"
);
foreach ( $rows as $row ) {
  echo esc_html( $row->comment_author );
}

Each read method accepts an optional output type. By default, rows come back as objects, so you read columns with $row->column_name. Pass ARRAY_A to get associative arrays instead, which some developers find easier to work with.

Use $wpdb->posts, $wpdb->users and similar properties for table names. They include the correct prefix automatically. For custom tables, use $wpdb->prefix followed by the table name.

Why should you always use $wpdb->prepare()?

prepare() escapes values safely and protects your query from SQL injection, which is one of the most serious security risks in WordPress code.

This applies to every value that could come from outside your code, including form fields, URL parameters, cookies and even data stored earlier by users. Treat all of it as untrusted.

Never drop user input straight into an SQL string. A visitor could craft input that changes your query and reads or deletes data.

prepare() uses placeholders:

  • %d for integers
  • %f for floats
  • %s for strings
  • %i for identifiers such as table or column names, in recent WordPress versions

The prepare() reference explains each placeholder. For LIKE searches, run the term through $wpdb->esc_like() first, then add the wildcards.

How do you insert, update or delete rows?

Use $wpdb->insert(), $wpdb->update() and $wpdb->delete(), which build safe queries from arrays of column names and values.

These helpers handle escaping for you:

global $wpdb;
$table = $wpdb->prefix . 'my_log';

$wpdb->insert( $table, array( 'message' => 'Started', 'created' => current_time( 'mysql' ) ), array( '%s', '%s' ) );

$wpdb->update( $table, array( 'message' => 'Done' ), array( 'id' => 5 ), array( '%s' ), array( '%d' ) );

$wpdb->delete( $table, array( 'id' => 5 ), array( '%d' ) );

After an insert, $wpdb->insert_id holds the new row's ID. If something fails, $wpdb->last_error shows the database error message.

Wrap related changes carefully. If a script updates thousands of rows, test it on a staging copy first and process records in batches, so one long query does not lock tables on a busy site.

For core data such as posts and users, prefer WordPress functions like wp_insert_post() and wp_update_user(). They run hooks and clear caches that raw queries skip.

How do you query the database in phpMyAdmin?

Open phpMyAdmin from your hosting panel, select the WordPress database, click the SQL tab, paste your query and click Go.

This is handy for quick checks, such as counting posts or finding a setting. If you are not sure which database belongs to your site, our guide on finding your WordPress database name shows how to check wp-config.php.

A read-only example that lists published pages:

SELECT ID, post_title, post_date
FROM wp_posts
WHERE post_type = 'page' AND post_status = 'publish'
ORDER BY post_date DESC;

Replace wp_ with your real prefix. The phpMyAdmin documentation covers the interface, and the MySQL SELECT reference explains query syntax.

Be careful with UPDATE and DELETE in phpMyAdmin. There is no undo. Run a SELECT with the same WHERE clause first to see which rows will change.

How do you query the database with WP-CLI?

Run wp db query followed by your SQL in quotes from the site folder, and WP-CLI connects with the details in wp-config.php.

Example:

wp db query "SELECT option_value FROM wp_options WHERE option_name = 'siteurl';"

The wp db query reference lists the options. WP-CLI also has wp db export for backups and wp search-replace for changing URLs safely.

For URL changes, do not run a plain SQL replace. Serialized data breaks if string lengths change. Our guide on search and replace in the WordPress database explains the safe method.

How do you see which queries a page runs?

Install the Query Monitor plugin, load the page, and open its Queries panel to see every database query, its time and the code that ran it.

Query Monitor is free and shows slow queries, duplicate queries and which plugin or theme caused each one. It is one of the best tools for finding performance problems.

Our guide on using Query Monitor explains its panels in detail.

Install it on staging or turn it off when you finish. It only shows data to administrators, but there is no reason to leave a debugging tool running on a live site longer than needed.

How do you keep custom queries fast?

Select only the columns you need, add LIMIT, avoid queries inside loops, and cache expensive results with transients or the object cache.

Practical tips:

  • Avoid SELECT * when you only need two columns
  • Filter by indexed columns such as ID, post_type and post_status
  • Be careful with meta queries on large sites, since wp_postmeta grows fast
  • Store expensive results with set_transient() for a few minutes
  • Run heavy reports from WP-CLI or cron rather than on page load
  • Use EXPLAIN in front of a SELECT to see whether indexes are used

Over time, cleaning old revisions and transients also helps. Our guide on optimizing the WordPress database covers safe cleanup.

Frequently asked questions

What is $wpdb in WordPress?

$wpdb is a global object created from the wpdb class. It connects to the WordPress database and provides methods to run queries, read results and insert, update or delete rows safely.

How do I find my WordPress table prefix?

Open wp-config.php and look for the table_prefix line. In PHP code, use $wpdb->prefix or properties such as $wpdb->posts instead of typing the prefix yourself.

Is it safe to run SQL queries on a live WordPress site?

Read-only SELECT queries are low risk, though heavy ones can slow the site. Queries that change data should only run after a backup, ideally on staging first, and with a tested WHERE clause.

Why does my $wpdb query return nothing?

Common causes are a wrong table prefix, a typo in a column name, or values that do not match. Print $wpdb->last_error and $wpdb->last_query to see the exact SQL and any database error.

Can I create custom tables in WordPress?

Yes. Plugins usually create them on activation with the dbDelta() function and a CREATE TABLE statement. Use the site's table prefix and keep the table structure documented for future updates.

Sources

  1. wpdb WordPress Code Reference
  2. wpdb::prepare() WordPress Code Reference
  3. wp db query WP-CLI Command Reference
  4. SELECT Statement MySQL Reference Manual
  5. phpMyAdmin Documentation phpMyAdmin
  6. Query Monitor WordPress.org Plugins

Is your product missing, or something out of date?

Tell us what to add or correct. We read every note and reply when we need a source. A message does not buy a ranking.

About the editors

Written and checked byWPLegible Editorial Team Independent WordPress reviews and guides

Researched from the primary sources listed above and checked against our editorial rules before publishing.