diff --git a/include/class.orm.php b/include/class.orm.php
index acb94853467f21c5442447029bc9b3f354d2b3ae..733b880ea6e7beca2505c33fb096508b3534966d 100644
--- a/include/class.orm.php
+++ b/include/class.orm.php
@@ -1443,7 +1443,7 @@ class QuerySet implements IteratorAggregate, ArrayAccess, Serializable, Countabl
         if (!is_array($annotations))
             $annotations = func_get_args();
         foreach ($annotations as $name=>$A) {
-            if ($A instanceof SqlAggregate) {
+            if ($A instanceof SqlFunction) {
                 if (is_int($name))
                     $name = $A->getFieldName();
                 $A->setAlias($name);
diff --git a/include/class.queue.php b/include/class.queue.php
index 189a7a84654a2bda283c60e0a49eae443ab142e8..950bff75c199abf8544a45df95f6ce2402d076ab 100644
--- a/include/class.queue.php
+++ b/include/class.queue.php
@@ -2072,18 +2072,41 @@ extends VerySimpleModel {
     }
 
     function applySort($query, $reverse=false) {
-	$root = ($q = $this->getQueue()) ? $q->getRoot() : 'Ticket';
+	    $root = ($q = $this->getQueue()) ? $q->getRoot() : 'Ticket';
         $fields = CustomQueue::getSearchableFields($root);
+
+        $keys = array();
         if ($primary = $fields[$this->primary]) {
             list(,$field) = $primary;
-            $query = $field->applyOrderBy($query, $reverse,
-                CustomQueue::getOrmPath($this->primary, $query));
+            $keys[] = array(CustomQueue::getOrmPath($this->primary, $query),
+                    $field);
         }
+
         if ($secondary = $fields[$this->secondary]) {
             list(,$field) = $secondary;
-            $query = $field->applyOrderBy($query, $reverse,
-                CustomQueue::getOrmPath($this->secondary, $query));
+            $keys[] = array(CustomQueue::getOrmPath($this->secondary,
+                        $query), $field);
+        }
+
+        if (count($keys) > 1) {
+            $fields = array();
+            foreach ($keys as $key) {
+                list($path, $field) = $key;
+                $fields[] = new SqlField($path);
+            }
+
+            $alias = sprintf('C%d', $this->getId());
+            $expr = call_user_func_array(array('SqlFunction', 'COALESCE'),
+                    $fields);
+            $query->annotate(array($alias => $expr));
+
+            $reverse = $reverse ? '-' : '';
+            $query = $query->order_by("{$reverse}{$alias}");
+        } else {
+            list($path, $field) = $keys[0];
+            $query = $field->applyOrderBy($query, $reverse, $path);
         }
+
         return $query;
     }