diff --git a/devel_generate/taxonomy.devel_generate.inc b/devel_generate/taxonomy.devel_generate.inc
index 35f7f42..a8e885d 100644
--- a/devel_generate/taxonomy.devel_generate.inc
+++ b/devel_generate/taxonomy.devel_generate.inc
@@ -15,22 +15,25 @@ function _taxonomy_devel_generate($object, $field, $instance, $bundle) {
   // will not result in any tags being added.
   $machine_name = $field['settings']['allowed_values'][0]['vocabulary'];
   $vocabulary = entity_load('taxonomy_vocabulary', $machine_name);
-  if ($max = db_query('SELECT MAX(tid) FROM {taxonomy_term_data} WHERE vid = :vid', array(':vid' => $vocabulary->vid))->fetchField()) {
-    $candidate = mt_rand(1, $max);
-    $query = db_select('taxonomy_term_data', 't');
-    $tid = $query
-              ->fields('t', array('tid'))
-              ->condition('t.vid', $vocabulary->vid, '=')
-              ->condition('t.tid', $candidate, '>=')
-              ->range(0,1)
-              ->execute()
-              ->fetchField();
+  $query = db_select('taxonomy_term_data', 't')
+    ->fields('t', array('tid'))
+    ->condition('t.vid', $vocabulary->id());
+
+  // Count the available terms for this vocabulary, keeping a static cache to
+  // avoid re-running the query.
+  $term_counts = &drupal_static(__FUNCTION__, array());
+  if (!isset($term_counts[$vocabulary->vid])) {
+    $term_counts[$vocabulary->id()] = (int) $query->countQuery()->execute()->fetchField();
+  }
+
+  if ($term_counts[$vocabulary->id()] > 0) {
+    // Select a random taxonomy term from this vocabulary.
+    $tid = $query->range(mt_rand(0, $term_counts[$vocabulary->id()]-1), 1)->execute()->fetchField();
     // If there are no terms for the taxonomy, the query will fail, in which
     // case we return NULL.
-    if ($tid === FALSE) {
-      return NULL;
+    if ($tid !== FALSE) {
+      $object_field['target_id'] = (int) $tid;
+      return $object_field;
     }
-    $object_field['tid'] = (int) $tid;
-    return $object_field;
   }
 }
