Drupal Tip #6: Removing Unused Taxonomy Terms

One not so great side effect of using free tagging with Drupal is that you will gradually build up a huge list of taxonomy terms that aren't being used. Typically this happens when nodes are delete that have some random taxonomy terms which arent used by any other nodes. There is a simple SQL statement you can run that will remove all unused taxonomy terms:

DELETE FROM term_data USING term_data LEFT JOIN term_node ON term_data.tid = term_node.tid WHERE term_node.tid IS NULL AND term_data.vid = vocabulary_id_#

Remember to add the Vocabulary ID you want to clean up. You wouldn't want to accidentally remove terms from a large static vocabulary. I use the SQL Cron module to run this statement automatically everytime cron.php is executed. This way I never have to worry about manually cleaning up my vocabularies.