The ORDER BY clause is used to control the order of result records.
You can sort result records by specifying attribute names or an arbitrary expression.
ORDER BY <Attr/Exp> [ASC/DESC] [,<AttrExp> [ASC/DESC]]*
where Attr/Exp is either an attribute name or an arbitrary expression.
Optionally, you can specify whether to sort in ascending (ASC) or descending (DESC) order. You can use any combination of values and sort orders. The absence of a direction implies ASC.
When an ORDER BY clause is used, NULL values will always sort after non-NULL values for a given attribute, and NaN (not-a-number) values will always sort after values other than NaN and NULL, regardless of the direction of the sort. Tied ranges (or all records in the absence of an ORDER BY clause) are ordered in an arbitrary but stable way: the same query will always return its results in the same order, as long as it is querying against the same version of the data. Data updates add or remove records from the order, but will not change the order of unmodified records.
RETURN Reps AS SELECT SUM(Amount) AS Total GROUP BY SalesRep ORDER BY Total DESC
String values are sorted in Unicode code point order.
Data of type geocode is sorted by latitude and then by longitude. To establish a more meaningful sort order when using geocode data, compute the distance from some point, and then sort by the distance.
/* Invalid statement */ DEFINE T1 AS SELECT ... AS foo RETURN T2 AS SELECT ... AS bar FROM T1 ORDER BY T1.foo /* not allowed */ /* Valid statement */ DEFINE T1 AS SELECT ... AS foo RETURN T2 AS SELECT ... AS bar FROM T1 ORDER BY T1[].foo /* allowed */
RETURN T AS SELECT ... AS bar FROM T1 ORDER BY SUM(bar) /* not allowed because of SUM aggregation function */ RETURN T AS SELECT ... AS bar FROM T1 ORDER BY ABS(bar) /* allowed */
EQL guarantees that the results of a statement are stable across queries. This means that:
For example, on a statement with no ORDER BY clause, queries that use PAGE(0, 10), then PAGE(10, 10), then PAGE(20, 10) will, with no updates, return successive groups of 10 records from the same arbitrary but stable result.
Note that ORDER BY only impacts the result of a RETURN clause, or the effect of a PAGE clause. ORDER BY on a DEFINE with no PAGE clause has no effect.