Spam comments are the worst. Even with Akismet active to prevent them from appearing on your site, they can still cause problems. That’s because the comment still gets stored and Akismet creates comment meta entries every time it does something. Over the course of time those unnecessary database entries can amount to hundreds of megabytes even on a reasonably small site. Multiply that by a couple hundred sites on a multisite network, and it can quickly start costing you real money in terms of hosting and causing serious problems when you back up your database.
Fortunately, MySQL can help you eliminate all this comment meta bloat with a few simple queries:
DELETE FROM wp_comments WHERE comment_approved = "spam"; DELETE FROM wp_commentmeta WHERE meta_key LIKE "akismet_%";
As always, make sure to back up your database before running any destructive queries on it.
Once you’ve deleted all of those Spam comments and Akismet meta entries, make sure to optimize the database tables.
OPTIMIZE TABLE wp_comments; OPTIMIZE TABLE wp_commentmeta;
If you’re running a multisite network, you’ll have to run the delete queries and the optimizations for each site, or at least each site which is causing problems. To determine which tables are the most bloated, you can run a query like this:
SELECT table_name AS "Tables", round(((data_length + index_length) / 1024 / 1024), 2) "Size in MB" FROM information_schema.TABLES WHERE table_schema = "YOUR_DATABASE_NAME" AND table_name LIKE "%comment%" ORDER BY (data_length + index_length) DESC;
This will list all comment and commentmeta tables sorted by size, from largest to smallest. Once you have a list of all tables you want to clean up, you can run the
OPTIMIZE queries for each table. Or, you could write a script to clear this generally useless data from your database at regular intervals.