Use MySQL Window Functions and CTEs for WordPress Analytics Queries

MySQL window functions and CTEs for WordPress reports

An editorial report often asks questions like “the top three posts of each category” or “the running total of comments per month”. With plain GROUP BY such questions need several queries and PHP loops. Window functions (ROW_NUMBER(), RANK(), SUM() OVER) and common table expressions (WITH) answer them in one query. They exist since MySQL 8.0 and MariaDB 10.2.

Problem: The editors want a report with the three most viewed posts per category, and a monthly chart of published posts with a running total, and the current PHP code runs one query per category.

Solution: Collect the base data in a CTE, rank the rows inside each category with ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...), keep the first three, and compute running totals with SUM(...) OVER (ORDER BY ...). Run the queries through $wpdb with the real table names.

The examples use the wp_ prefix and a view counter stored in the post meta ha_views.

Top three posts per category

WITH post_views AS (
    SELECT p.ID, p.post_title, t.name AS category,
           CAST(COALESCE(pm.meta_value, '0') AS UNSIGNED) AS views
    FROM wp_posts p
    JOIN wp_term_relationships tr ON tr.object_id = p.ID
    JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'category'
    JOIN wp_terms t ON t.term_id = tt.term_id
    LEFT JOIN wp_postmeta pm ON pm.post_id = p.ID AND pm.meta_key = 'ha_views'
    WHERE p.post_type = 'post' AND p.post_status = 'publish'
),
ranked AS (
    SELECT post_views.*,
           ROW_NUMBER() OVER (PARTITION BY category ORDER BY views DESC) AS place
    FROM post_views
)
SELECT category, place, post_title, views
FROM ranked
WHERE place <= 3
ORDER BY category, place;

PARTITION BY restarts the numbering for each category; the rows are not collapsed as with GROUP BY. ROW_NUMBER() gives ties different numbers, RANK() gives them the same number and leaves a gap after them. The ranking cannot be filtered in the same SELECT, which is why the second CTE exists.

Posts per month with a running total

WITH monthly AS (
    SELECT DATE_FORMAT(post_date, '%Y-%m') AS month, COUNT(*) AS posts
    FROM wp_posts
    WHERE post_type = 'post' AND post_status = 'publish'
    GROUP BY month
)
SELECT month, posts,
       SUM(posts) OVER (ORDER BY month) AS total,
       posts - LAG(posts) OVER (ORDER BY month) AS change_from_previous
FROM monthly
ORDER BY month;

LAG() reads the value of the previous row, so the change from month to month needs no self-join.

In PHP

global $wpdb;
$sql = "WITH monthly AS (
            SELECT DATE_FORMAT(post_date, '%%Y-%%m') AS month, COUNT(*) AS posts
            FROM {$wpdb->posts}
            WHERE post_type = %s AND post_status = 'publish'
            GROUP BY month
        )
        SELECT month, posts, SUM(posts) OVER (ORDER BY month) AS total FROM monthly ORDER BY month";
$rows = $wpdb->get_results( $wpdb->prepare( $sql, 'post' ) );

Inside prepare(), the % of DATE_FORMAT must be doubled. Check the server version first: on MySQL 5.7 these queries fail with a syntax error. Grouping basics: GROUP BY and ORDER BY; joins: MySQL joins with WordPress tables.

NOTE: Reports like these read the whole posts table. Run them in the admin or from WP-CLI, cache the result in a transient for an hour, and never put them on a public page that every visitor loads.