Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
Wordpress

WordPress: Run Custom SQL Queries with $wpdb Object

- 31.05.26 - ErcanOPAK

💾 WP_Query Too Slow? Go Direct!

WP_Query is convenient but slow for complex reports. $wpdb runs raw SQL. Faster, more powerful, full control.

📝 Basic $wpdb

global $wpdb;

// Get single value
$user_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->users}");

// Get single row
$user = $wpdb->get_row("SELECT * FROM {$wpdb->users} WHERE ID = 123");

// Get all results (array of objects)
$users = $wpdb->get_results("SELECT * FROM {$wpdb->users} LIMIT 10");

// Get column
$emails = $wpdb->get_col("SELECT user_email FROM {$wpdb->users}");

// Insert (safe, auto-escaped)
$wpdb->insert(
    $wpdb->postmeta,
    [
        'post_id' => 123,
        'meta_key' => 'custom_field',
        'meta_value' => 'Hello World'
    ]
);

// Update
$wpdb->update(
    $wpdb->posts,
    ['post_title' => 'New Title'],
    ['ID' => 123]
);

🎯 Complex Queries

// Top 10 products by sales
$top_products = $wpdb->get_results("
    SELECT p.ID, p.post_title, SUM(oi.meta_value) as total_sales
    FROM {$wpdb->posts} p
    JOIN {$wpdb->postmeta} oi ON p.ID = oi.post_id
    WHERE p.post_type = 'product' 
      AND p.post_status = 'publish'
      AND oi.meta_key = '_order_total'
    GROUP BY p.ID
    ORDER BY total_sales DESC
    LIMIT 10
");

// Search with prepared statement (safe!)
$search = '%' . $wpdb->esc_like($search_term) . '%';
$results = $wpdb->get_results($wpdb->prepare("
    SELECT * FROM {$wpdb->posts}
    WHERE post_title LIKE %s
    AND post_status = 'publish'
", $search));

✅ Best Practices

  • Always use $wpdb->prepare() for user input (prevents SQL injection)
  • Use $wpdb->prefix for table names (multisite compatible)
  • Check for errors: if ($wpdb->last_error) { … }
  • For reports, consider caching results with transients

“WP_Query took 5 seconds for report. Raw SQL with $wpdb took 0.2 seconds. 25x faster. Know when to bypass WP_Query.”

— Performance Consultant

Related posts:

WordPress: Fix the Block Editor Losing Your Cursor Position Every Time Autosave Runs Because Autosav...

WordPress: Fix the Block Editor Losing Your Cursor Position Every Time Autosave Runs Because Autosav...

WordPress: Use Query Monitor to Debug Performance Issues

WordPress: Use Query Monitor to Debug Performance Issues

WordPress: Control Heartbeat API to Reduce Server Load

WordPress: Control Heartbeat API to Reduce Server Load

Views: 15
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Photoshop: Batch Process Hundreds of Photos with Actions
Kubernetes: Use Pod Affinity to Schedule Related Pods Together

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 996 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 995 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 866 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com