10.2. Order by
ORDER BY is a sub-clause following
WITH, and it specifies that the output should be sorted and how.
Note that you can not sort on nodes or relationships, just on properties on these.
ORDER BY relies on comparisons to sort the output, see the section called “Ordering and Comparison of Values”.
In terms of scope of identifiers,
ORDER BY follows special rules, depending on if the projecting
WITH clause is either aggregating or
If it is an aggregating or
DISTINCT projection, only the identifiers available in the projection are available.
If the projection does not alter the output cardinality (which aggregation and
DISTINCT do), identifiers available from before the projecting clause are also available.
When the projection clause shadows already existing identifiers, only the new identifiers are available.
Lastly, it is not allowed to use aggregating expressions in the
ORDER BY sub-clause if they are not also listed in the projecting clause.
This last rule is to make sure that
ORDER BY does not change the results, only the order of them.
Order nodes by property
ORDER BY is used to sort the output.
MATCH (n) RETURN n ORDER BY n.name
The nodes are returned, sorted by their name.
Order nodes by multiple properties
You can order by multiple properties by stating each identifier in the
ORDER BY clause. Cypher will sort the result by the first identifier listed, and for equals values, go to the next property in the
ORDER BY clause, and so on.
MATCH (n) RETURN n ORDER BY n.age, n.name
This returns the nodes, sorted first by their age, and then by their name.
Order nodes in descending order
DESC[ENDING] after the identifier to sort on, the sort will be done in reverse order.
MATCH (n) RETURN n ORDER BY n.name DESC
The example returns the nodes, sorted by their name reversely.
When sorting the result set,
NULL will always come at the end of the result set for ascending sorting, and first when doing descending sort.
MATCH (n) RETURN n.length, n ORDER BY n.length
The nodes are returned sorted by the length property, with a node without that property last.