diff --git a/core/modules/node/node.module b/core/modules/node/node.module
index 1e1084e..7088f1f 100644
--- a/core/modules/node/node.module
+++ b/core/modules/node/node.module
@@ -2695,12 +2695,10 @@ function node_access_view_all_nodes($account = NULL) {
 
     $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->condition(db_and()
+        ->condition('gid', $gids, 'IN')
+        ->condition('realm', $realm)
+      );
     }
     if (count($grants) > 0 ) {
       $query->condition($grants);
@@ -2792,12 +2790,10 @@ function node_query_node_access_alter(AlterableInterface $query) {
       // 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->condition(db_and()
+          ->condition('na.gid', $gids, 'IN')
+          ->condition('na.realm', $realm)
+        );
       }
 
       // Attach conditions to the subquery for nodes.
diff --git a/core/modules/system/system.api.php b/core/modules/system/system.api.php
index aa79df9..210c066 100644
--- a/core/modules/system/system.api.php
+++ b/core/modules/system/system.api.php
@@ -2511,19 +2511,17 @@ function hook_query_TAG_alter(Drupal\Core\Database\Query\AlterableInterface $que
     if (!user_access('bypass node access')) {
       // The node_access table has the access grants for any given node.
       $access_alias = $query->join('node_access', 'na', '%alias.nid = n.nid');
-      $or = db_or();
+      $grants = db_or();
       // If any grant exists for the specified user, then user has access to the node for the specified operation.
       foreach (node_access_grants($op, $query->getMetaData('account')) as $realm => $gids) {
-        foreach ($gids as $gid) {
-          $or->condition(db_and()
-            ->condition($access_alias . '.gid', $gid)
-            ->condition($access_alias . '.realm', $realm)
-          );
-        }
+        $grants->condition(db_and()
+          ->condition($access_alias . '.gid', $gids, 'IN')
+          ->condition($access_alias . '.realm', $realm)
+        );
       }
 
-      if (count($or->conditions())) {
-        $query->condition($or);
+      if (count($grants->conditions())) {
+        $query->condition($grants);
       }
 
       $query->condition($access_alias . 'grant_' . $op, 1, '>=');
