MySQL views explained with WordPress database examples

MySQL views with WordPress tables: when they help and when they do not

A view is a saved SELECT that can be queried like a table. For reports that join the posts, meta and term tables again and again, a view keeps the complicated part in one place: SELECT * FROM ha_category_stats instead of three joins in every query. In WordPress projects views are useful for reporting and exports, and a poor fit for code that runs on every page.

Problem: Several reports and an export script repeat the same joins over posts and categories, and every copy of the query is slightly different.

Solution: Create a view with CREATE OR REPLACE VIEW for the shared query, query it in the reports, and keep the view definition in the plugin’s migrations so it uses the site’s table prefix. Use plain queries in code that ships to other sites.

The examples use the wp_ prefix; replace it with yours.

A view for category statistics

CREATE OR REPLACE VIEW ha_category_stats AS
SELECT t.term_id,
       t.name                   AS category,
       COUNT(p.ID)              AS published_posts,
       MAX(p.post_date)         AS latest_post
FROM wp_terms t
JOIN wp_term_taxonomy tt       ON tt.term_id = t.term_id AND tt.taxonomy = 'category'
LEFT JOIN wp_term_relationships tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
LEFT JOIN wp_posts p           ON p.ID = tr.object_id AND p.post_type = 'post' AND p.post_status = 'publish'
GROUP BY t.term_id, t.name;
SELECT category, published_posts, latest_post
FROM ha_category_stats
WHERE published_posts > 0
ORDER BY latest_post DESC;

A view stores no data: every query runs the underlying SELECT. It is always current, and it is exactly as fast or slow as the query it contains.

Creating it from a plugin

<?php
function ha_create_views() {
    global $wpdb;

    $wpdb->query( "CREATE OR REPLACE VIEW {$wpdb->prefix}ha_category_stats AS
        SELECT t.term_id, t.name AS category, COUNT(p.ID) AS published_posts, MAX(p.post_date) AS latest_post
        FROM {$wpdb->terms} t
        JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id AND tt.taxonomy = 'category'
        LEFT JOIN {$wpdb->term_relationships} tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
        LEFT JOIN {$wpdb->posts} p ON p.ID = tr.object_id AND p.post_type = 'post' AND p.post_status = 'publish'
        GROUP BY t.term_id, t.name" );
}

Call it from the plugin’s activation or migration step, and drop the view on uninstall (DROP VIEW IF EXISTS).

The catches

  • Privileges. Creating a view needs the CREATE VIEW privilege, which many shared hosts do not give the WordPress database user. The plugin must work, or at least fail clearly, without it.
  • Definer. A view is saved with the database user who created it as its DEFINER. After a migration to a server where that user does not exist, querying the view fails with “The user specified as a definer does not exist”. Database dumps from one host imported on another run into this often.
  • Backups and tools. Some backup and migration plugins copy only tables and skip views, or restore them before the tables they depend on.
  • No indexes. A view cannot have its own indexes. For a report that is slow even as a plain query, a summary table filled by a cron job is the better tool.

For a single site you control (a reporting database, an export job), views are a clean way to share queries. For a plugin installed on many unknown hosts, the same query in PHP, built with $wpdb table names, is more robust.

NOTE: Do not make a view look like a core table (wp_post_stats): give it your plugin’s prefix, so nobody confuses it with WordPress data or deletes it in a cleanup of “unknown tables”.