diff --git a/metatag.install b/metatag.install
index 2df41f4..808f853 100644
--- a/metatag.install
+++ b/metatag.install
@@ -317,34 +317,49 @@ function metatag_update_7006() {
  * of Metatag may have failed to purge these.
  */
 function metatag_update_7007() {
-  $result = db_query("DELETE m
-    FROM {metatag} m
-    LEFT OUTER JOIN {node} n
-    	ON m.entity_id=n.nid
-    WHERE m.entity_type='node'
-    	AND n.nid IS NULL");
+  $subquery = db_select('metatag', 'm')
+    ->fields('m', array('entity_id'))
+    ->condition('m.entity_type', 'node')
+    ->leftJoin('node', 'n', 'm.entity_id=n.nid')
+    ->isNull('n.nid');
+
+  $result = db_delete('metatag')
+    ->condition('entity_type', 'node')
+    ->condition('entity_id', $subquery)
+    ->execute();
+
   if ($result->rowCount() > 0) {
     drupal_set_message(t('Removed @count meta tag record(s) for nodes that had been purged.', array('@count' => $result->rowCount())));
   }
 
-  $result = db_query("DELETE m
-    FROM {metatag} m
-    LEFT OUTER JOIN {users} u
-    	ON m.entity_id=u.uid
-    WHERE m.entity_type='user'
-    	AND u.uid IS NULL");
+  $subquery = db_select('metatag', 'm')
+    ->fields('m', array('entity_id'))
+    ->condition('m.entity_type', 'user')
+    ->leftJoin('user', 'u', 'm.entity_id=u.uid')
+    ->isNull('u.uid');
+
+  $result = db_delete('metatag')
+    ->condition('entity_type', 'user')
+    ->condition('entity_id', $subquery)
+    ->execute();
+
   if ($result->rowCount() > 0) {
     drupal_set_message(t('Removed @count meta tag record(s) for users that had been purged.', array('@count' => $result->rowCount())));
   }
 
   // Only run this if the Taxonomy module is enabled.
   if (module_exists('taxonomy')) {
-    $result = db_query("DELETE m
-      FROM {metatag} m
-      LEFT OUTER JOIN {taxonomy_term_data} t
-      	ON m.entity_id=t.tid
-      WHERE m.entity_type='taxonomy_term'
-      	AND t.tid IS NULL");
+    $subquery = db_select('metatag', 'm')
+      ->fields('m', array('entity_id'))
+      ->condition('m.entity_type', 'taxonomy_term')
+      ->leftJoin('taxonomy_term_data', 't', 'm.entity_id=t.tid')
+      ->isNull('t.tid');
+
+    $result = db_delete('metatag')
+      ->condition('entity_type', 'taxonomy_term')
+      ->condition('entity_id', $subquery)
+      ->execute();
+
     if ($result->rowCount() > 0) {
       drupal_set_message(t('Removed @count meta tag record(s) for taxonomy terms that had been purged.', array('@count' => $result->rowCount())));
     }
