Technical Mid Level

When is it appropriate to use $wpdb for direct database queries instead of WordPress API functions? How do you do it safely?

Quick Tip

Show the safety pattern: "I always use $wpdb->prepare() with typed placeholders. For custom tables, I use $wpdb->prefix to support multisite. I reach for $wpdb only when WP_Query or get_posts cannot express what I need."

What good answers include

Use $wpdb when WordPress API functions cannot express the query you need — complex joins, aggregations, bulk operations, or custom tables. Safety: always use $wpdb->prepare() with placeholders (%s, %d, %f) to prevent SQL injection. Use $wpdb->prefix for table names to support multisite. Common methods: $wpdb->get_results(), $wpdb->get_var(), $wpdb->get_row(), $wpdb->insert(), $wpdb->update(), $wpdb->delete(). Strong candidates discuss: when get_posts/WP_Query is insufficient, creating custom tables versus using postmeta, using dbDelta() for table creation, and the WPDB class methods for different return types.

What interviewers are looking for

Tests database skills in WordPress context. Candidates who never use $wpdb may not know how to solve complex data problems. Those who use it without prepare() are a security risk. Look for candidates who know when the WordPress API is insufficient and can write safe SQL.

← All WordPress questions