diff --git a/modules/node/node.module b/modules/node/node.module
index 51ec8c3..acb4093 100644
--- a/modules/node/node.module
+++ b/modules/node/node.module
@@ -3386,7 +3386,31 @@ function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE)
       // Only write grants; denies are implicit.
       if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
         $grant['nid'] = $node->nid;
-        $query->values($grant);
+
+        $count = db_select('node_access')
+                ->condition('nid', $grant['nid'])
+                ->condition('gid', $grant['gid'])
+                ->condition('realm', $grant['realm'])
+                ->countQuery()->execute()->fetchField();
+
+        // If same node, grants and realm. Do an update query.
+        if ($count > 0) {
+          $update_query = db_update('node_access')
+            ->condition('nid', $grant['nid'])
+            ->condition('gid', $grant['gid'])
+            ->condition('realm', $grant['realm'])
+            ->fields(array(
+              'realm' => $grant['realm'],
+              'gid' => $grant['gid'],
+              'grant_view' => $grant['grant_view'],
+              'grant_update' => $grant['grant_update'],
+              'grant_delete' => $grant['grant_delete'],
+            ));
+          $update_query->execute();
+        }
+        else {
+          $query->values($grant);
+        }
       }
     }
     $query->execute();
