MySQL Table Partitioning for Large WordPress Databases

MySQL partitioning for large WordPress log tables

Partitioning splits a table into separate physical parts by a rule, for example one part per month, while queries still see one table. For WordPress, the useful case is not wp_posts or wp_postmeta, but the large append-only tables that plugins create: logs, statistics, events. There, partitions make old data cheap to delete and keep queries on recent data fast.

Problem: A statistics plugin writes 3 million rows per month into wp_ha_page_views. The nightly cleanup DELETE FROM ... WHERE viewed_at < NOW() - INTERVAL 6 MONTH runs for 40 minutes, locks the table and makes the binary log explode.

Solution: Create the log table with PARTITION BY RANGE on the date, with the date column in the primary key, add a partition for each new month ahead of time and remove old months with ALTER TABLE ... DROP PARTITION, which deletes a month in a fraction of a second. Leave the WordPress core tables unpartitioned.

Why not the core tables

Older tutorials partition wp_posts by year. Every unique key of a partitioned table must contain the partitioning column, so the primary key ID has to become (ID, post_year), and the table loses its guarantee that an ID is unique. Full-text indexes and foreign keys do not work on partitioned InnoDB tables at all. WordPress queries posts mostly by ID, slug, type and status, not by date, so most queries would have to look into every partition anyway. Updates of WordPress or plugins that alter these tables can also fail on a partitioned table. Indexes are the right tool for slow core tables: MySQL indexes for WordPress queries.

The partitioned table

CREATE TABLE wp_ha_page_views (
    id        BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id   BIGINT UNSIGNED NOT NULL,
    viewed_at DATETIME        NOT NULL,
    referrer  VARCHAR(191)    NOT NULL DEFAULT '',
    PRIMARY KEY (id, viewed_at),
    KEY post_time (post_id, viewed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
PARTITION BY RANGE COLUMNS (viewed_at) (
    PARTITION p2024_11 VALUES LESS THAN ('2024-12-01'),
    PARTITION p2024_12 VALUES LESS THAN ('2025-01-01'),
    PARTITION p2025_01 VALUES LESS THAN ('2025-02-01'),
    PARTITION p_future VALUES LESS THAN (MAXVALUE)
);

RANGE COLUMNS works directly on a DATETIME column, no function needed. The primary key contains viewed_at because of the rule above; id stays auto-incremented and in practice unique. p_future catches rows beyond the last defined month, so an insert never fails because a partition is missing.

Queries that use only some partitions

EXPLAIN SELECT post_id, COUNT(*)
FROM wp_ha_page_views
WHERE viewed_at >= '2025-01-01' AND viewed_at < '2025-02-01'
GROUP BY post_id;
-- partitions: p2025_01

When the WHERE clause restricts the partitioning column, MySQL reads only the matching partitions (“partition pruning”); the partitions column of EXPLAIN shows which. A condition on DATE(viewed_at) instead of a range on the column prevents pruning, the same way it prevents index use.

Monthly maintenance

-- split the catch-all partition to create next month
ALTER TABLE wp_ha_page_views REORGANIZE PARTITION p_future INTO (
    PARTITION p2025_02 VALUES LESS THAN ('2025-03-01'),
    PARTITION p_future VALUES LESS THAN (MAXVALUE)
);

-- remove a whole month of old data instantly
ALTER TABLE wp_ha_page_views DROP PARTITION p2024_11;

-- size per partition
SELECT partition_name, table_rows, ROUND(data_length / 1024 / 1024) AS data_mb
FROM information_schema.PARTITIONS
WHERE table_schema = DATABASE() AND table_name = 'wp_ha_page_views';

Splitting p_future while it is still empty is instant. DROP PARTITION removes the data files of that month instead of deleting rows one by one: no long lock, no undo log, a tiny entry in the binary log. A daily WP-Cron event or a system cron job can run both statements a few days before the month changes.

function ha_rotate_view_partitions(): void {
    global $wpdb;
    $table = $wpdb->prefix . 'ha_page_views';
    $next  = new DateTimeImmutable( 'first day of next month' );
    $name  = 'p' . $next->format( 'Y_m' );
    $until = $next->modify( '+1 month' )->format( 'Y-m-d' );

    $exists = $wpdb->get_var( $wpdb->prepare(
        'SELECT COUNT(*) FROM information_schema.PARTITIONS WHERE table_schema = DATABASE() AND table_name = %s AND partition_name = %s',
        $table,
        $name
    ) );
    if ( ! $exists ) {
        $wpdb->query( "ALTER TABLE {$table} REORGANIZE PARTITION p_future INTO (
            PARTITION {$name} VALUES LESS THAN ('{$until}'), PARTITION p_future VALUES LESS THAN (MAXVALUE) )" );
    }
}

The partition name and the date are built from the current date in code, not from input, so they can go into the statement directly.

NOTE: Partitioning pays off from tens of millions of rows; below that, a good index and a cleanup in small batches (DELETE ... LIMIT 10000 in a loop) are simpler. Some managed MySQL services and older shared hosts disable partitioning, so check SELECT PLUGIN_STATUS FROM information_schema.PLUGINS WHERE PLUGIN_NAME = 'partition' (MariaDB) or try it on a copy first. Table maintenance in general: ANALYZE, OPTIMIZE and the slow query log.