sql query to delete orphaned post meta in your WordPress database

March 6, 2013 at 6:02 pm

After an intensive use of your WordPress blog (creating posts, editing posts, and deleting posts) your database will contain thousands of rows of useless meta data. Here is a simple SQL query to delete orphaned post meta on your database.

Just run the following query on your WordPress database to delete orphaned post meta. Don’t forget to replace the table prefix wp_ if your database is using another prefix.
And of course, create a backup of your database before running the query!

DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL

Thanks to Patrick Rauland for submitting this useful recipe!

Tags: