diff --git a/includes/database/select.inc b/includes/database/select.inc
index 3c700a5..6e16d79 100644
--- a/includes/database/select.inc
+++ b/includes/database/select.inc
@@ -1528,7 +1528,11 @@ class SelectQuery extends Query implements SelectQueryInterface {
     $comments = $this->connection->makeComment($this->comments);
 
     // SELECT
-    $query = $comments . 'SELECT ';
+    $query = $comments;
+    if ($this->union) {
+      $query .= ' ( ';
+    }
+    $query .= 'SELECT ';
     if ($this->distinct) {
       $query .= 'DISTINCT ';
     }
@@ -1615,18 +1619,19 @@ class SelectQuery extends Query implements SelectQueryInterface {
       $query .= "\nLIMIT " . (int) $this->range['length'] . " OFFSET " . (int) $this->range['start'];
     }
 
+    if ($this->forUpdate) {
+      $query .= ' FOR UPDATE';
+    }
+
     // UNION is a little odd, as the select queries to combine are passed into
     // this query, but syntactically they all end up on the same level.
     if ($this->union) {
-      foreach ($this->union as $union) {
-        $query .= ' ' . $union['type'] . ' ' . (string) $union['query'];
+      $query .= ' )';
+      foreach ($this->union as $index => $union) {
+        $query .= ' ' . $union['type'] . ' (' . (string) $union['query'] . ')';
       }
     }
 
-    if ($this->forUpdate) {
-      $query .= ' FOR UPDATE';
-    }
-
     return $query;
   }
 
