diff --git a/modules/node/node.module b/modules/node/node.module
index 8f247cd..e8c494b 100644
--- a/modules/node/node.module
+++ b/modules/node/node.module
@@ -3046,18 +3046,12 @@ function node_access($op, $node, $account = NULL) {
       $query->condition($nids);
       $query->range(0, 1);
 
-      $grants = db_or();
-      foreach (node_access_grants($op, $account) as $realm => $gids) {
-        foreach ($gids as $gid) {
-          $grants->condition(db_and()
-            ->condition('gid', $gid)
-            ->condition('realm', $realm)
-          );
-        }
-      }
+      $grants = node_add_node_grants_to_query(node_access_grants($op, $account));
+
       if (count($grants) > 0) {
         $query->condition($grants);
       }
+
       $result =  (bool) $query
         ->execute()
         ->fetchField();
@@ -3075,6 +3069,20 @@ function node_access($op, $node, $account = NULL) {
   return FALSE;
 }
 
+function node_add_node_grants_to_query($node_access_grants) {
+  $grants = db_or();
+  foreach ($node_access_grants as $realm => $gids) {
+    if (!empty($gids)) {
+      $grants->condition(db_and()
+        ->condition('gid', $gids, 'IN')
+        ->condition('realm', $realm)
+      );
+    }
+  }
+
+  return $grants;
+}
+
 /**
  * Implements hook_node_access().
  */
@@ -3243,15 +3251,8 @@ function node_access_view_all_nodes($account = NULL) {
       ->condition('nid', 0)
       ->condition('grant_view', 1, '>=');
 
-    $grants = db_or();
-    foreach (node_access_grants('view', $account) as $realm => $gids) {
-      foreach ($gids as $gid) {
-        $grants->condition(db_and()
-          ->condition('gid', $gid)
-          ->condition('realm', $realm)
-        );
-      }
-    }
+    $grants = node_add_node_grants_to_query(node_access_grants('view', $account));
+
     if (count($grants) > 0 ) {
       $query->condition($grants);
     }
@@ -3402,17 +3403,7 @@ function _node_query_node_access_alter($query, $type) {
       $subquery = db_select('node_access', 'na')
        ->fields('na', array('nid'));
 
-      $grant_conditions = db_or();
-      // If any grant exists for the specified user, then user has access
-      // to the node for the specified operation.
-      foreach ($grants as $realm => $gids) {
-        foreach ($gids as $gid) {
-          $grant_conditions->condition(db_and()
-            ->condition('na.gid', $gid)
-            ->condition('na.realm', $realm)
-          );
-        }
-      }
+      $grant_conditions = node_add_node_grants_to_query(node_access_grants($op, $account));
 
       // Attach conditions to the subquery for nodes.
       if (count($grant_conditions->conditions())) {
