Title: Best practices for database queries
Author: WordPress VIP Documentation
Published: September 18, 2020
Last modified: December 29, 2025

---

 1. [Databases](https://docs.wpvip.com/databases/)
 2. [Optimize database queries](https://docs.wpvip.com/databases/optimize-queries/)
 3. Best practices for database queries

#  Best practices for database queries

WordPress API functions should be used instead of direct database queries for fetching
and manipulating data whenever possible. In a situation where WordPress API functions
cannot be used—and direct database queries cannot be avoided—follow these best practices:

 * Use filters to adjust queries when needed. There are many filters in `/wp-includes/
   query.php` that are available to hook into. Filters such as `posts_where` can
   help to adjust the default queries performed by [WP_Query](https://developer.wordpress.org/reference/classes/wp_query/).
   This helps keep code compatible with other plugins.
 * Make sure that all queries are protected against SQL injection by making use 
   of `[$wpdb->prepare](https://developer.wordpress.org/reference/classes/wpdb/#Protect_Queries_Against_SQL_Injection_Attacks)`
   and other escaping operations like [the `esc_sql()` function](https://developer.wordpress.org/reference/functions/esc_sql/)
   and [the `wpdb::esc_like()` method](https://developer.wordpress.org/reference/classes/wpdb/esc_like/).
 * Avoid cross-table queries, especially queries that could contain huge datasets(
   e.g. negating taxonomy queries like the `-cat` option to exclude posts of a certain
   category). Cross-table queries can cause a huge load on the database servers.
 * Though many operations can be made on the database side, code will scale much
   better by keeping database queries simple and performing necessary calculations
   and logic in PHP.
 * Avoid using `DISTINCT`, `GROUP`, or other query statements that cause the generation
   of temporary tables to deliver the results.
 * Be aware of the amount of data that is requested. Include defensive limits.
 * When creating queries in a development environment, [use the `EXPLAIN` statement](https://dev.mysql.com/doc/refman/8.0/en/using-explain.html)
   to examine the queries for performance issues. Confirm that indexes are being
   used.
 * Cache the results of queries in [the object cache](https://docs.wpvip.com/caching/object-cache/)
   where it makes sense.

Last updated: December 29, 2025