diff --git a/include/class.orm.php b/include/class.orm.php
index 9798d94819db755e51664e83e739b4ec4dfde6f6..72495a85a2b97db1c352bb993d51131953990b71 100644
--- a/include/class.orm.php
+++ b/include/class.orm.php
@@ -2580,29 +2580,31 @@ class MySqlCompiler extends SqlCompiler {
 
         $joins = $this->getJoins($queryset);
 
+        $sql = 'SELECT '.implode(', ', $fields).' FROM '
+            .$table.$joins.$where.$group_by.$having.$sort;
         // UNIONS
-        $unions='';
         if ($queryset->chain) {
+            // If the main query is sorted, it will need parentheses
+            if ($parens = (bool) $sort)
+                $sql = "($sql)";
             foreach ($queryset->chain as $qs) {
                 list($qs, $all) = $qs;
                 $q = $qs->getQuery(array('nosort' => true));
                 // Rewrite the parameter numbers so they fit the parameter numbers
                 // of the current parameters of the $compiler
                 $self = $this;
-                $sql = preg_replace_callback("/:(\d+)/",
+                $S = preg_replace_callback("/:(\d+)/",
                 function($m) use ($self, $q) {
                     $self->params[] = $q->params[$m[1]-1];
                     return ':'.count($self->params);
                 }, $q->sql);
                 // Wrap unions in parentheses if they are windowed or sorted
-                if ($qs->isWindowed() || count($qs->getSortFields()))
-                    $sql = "($sql)";
-                $unions .= ' UNION '.($all ? 'ALL ' : '').$sql;
+                if ($parens || $qs->isWindowed() || count($qs->getSortFields()))
+                    $S = "($S)";
+                $sql .= ' UNION '.($all ? 'ALL ' : '').$S;
             }
         }
 
-        $sql = 'SELECT '.implode(', ', $fields).' FROM '
-            .$table.$joins.$where.$group_by.$having.$unions.$sort;
         if ($queryset->limit)
             $sql .= ' LIMIT '.$queryset->limit;
         if ($queryset->offset)
diff --git a/include/staff/tickets.inc.php b/include/staff/tickets.inc.php
index a388e5cad52f243bf16189a66e3b0df7f45eb49f..2742d39a71993b1d8d122acb6ca2d3551384d12a 100644
--- a/include/staff/tickets.inc.php
+++ b/include/staff/tickets.inc.php
@@ -196,21 +196,6 @@ $pageNav = new Pagenate($count, $page, PAGE_LIMIT);
 $pageNav->setURL('tickets.php', $args);
 $tickets = $pageNav->paginate($tickets);
 
-// Rewrite $tickets to use a nested query, which will include the LIMIT part
-// in order to speed the result
-//
-// ATM, advanced search with keywords doesn't support the subquery approach
-if ($use_subquery) {
-    $orig_tickets = clone $tickets;
-    $tickets2 = TicketModel::objects();
-    $tickets2->values = $tickets->values;
-    $tickets2->filter(array('ticket_id__in' => $tickets->values_flat('ticket_id')));
-
-    // Transfer the order_by from the original tickets
-    $tickets2->order_by($orig_tickets->getSortFields());
-    $tickets = $tickets2;
-}
-
 // Apply requested sorting
 $queue_sort_key = sprintf(':Q%s:%s:sort', ObjectModel::OBJECT_TYPE_TICKET, $queue_name);
 
@@ -299,6 +284,17 @@ case 'updated':
     break;
 }
 
+// Rewrite $tickets to use a nested query, which will include the LIMIT part
+// in order to speed the result
+$orig_tickets = clone $tickets;
+$tickets2 = TicketModel::objects();
+$tickets2->values = $tickets->values;
+$tickets2->filter(array('ticket_id__in' => $tickets->values_flat('ticket_id')));
+
+// Transfer the order_by from the original tickets
+$tickets2->order_by($orig_tickets->getSortFields());
+$tickets = $tickets2;
+
 // Save the query to the session for exporting
 $_SESSION[':Q:tickets'] = $tickets;
 
@@ -307,6 +303,7 @@ TicketForm::ensureDynamicDataView();
 // Select pertinent columns
 // ------------------------------------------------------------
 $tickets->values('lock__staff_id', 'staff_id', 'isoverdue', 'team_id', 'ticket_id', 'number', 'cdata__subject', 'user__default_email__address', 'source', 'cdata__priority__priority_color', 'cdata__priority__priority_desc', 'status_id', 'status__name', 'status__state', 'dept_id', 'dept__name', 'user__name', 'lastupdate', 'isanswered', 'staff__firstname', 'staff__lastname', 'team__name');
+
 // Add in annotations
 $tickets->annotate(array(
     'collab_count' => TicketThread::objects()