15.14. Order by

15.14.1. Order nodes by property
15.14.2. Order nodes by multiple properties
15.14.3. Order nodes in descending order
15.14.4. Ordering null

To sort the output, use the ORDER BY clause. Note that you can not sort on nodes or relationships, just on properties on these.

Figure 15.7. Graph


15.14.1. Order nodes by property

ORDER BY is used to sort the output.

Query. 

START n=node(3,1,2)
RETURN n
ORDER BY n.name

The nodes are returned, sorted by their name.

Result

n
0 row
0 ms

(empty result)


Try this query live. (1) {"age":34,"length":170,"name":"A"} (2) {"age":34,"name":"B"} (3) {"age":32,"length":185,"name":"C"} (1)-[:KNOWS]->(2) {} (2)-[:KNOWS]->(3) {} start n=node(3,1,2) return n order by n.name

15.14.2. 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.

Query. 

START n=node(3,1,2)
RETURN n
ORDER BY n.age, n.name

This returns the nodes, sorted first by their age, and then by their name.

Result

n
0 row
0 ms

(empty result)


Try this query live. (1) {"age":34,"length":170,"name":"A"} (2) {"age":34,"name":"B"} (3) {"age":32,"length":185,"name":"C"} (1)-[:KNOWS]->(2) {} (2)-[:KNOWS]->(3) {} start n=node(3,1,2) return n order by n.age, n.name

15.14.3. Order nodes in descending order

By adding DESC[ENDING] after the identifier to sort on, the sort will be done in reverse order.

Query. 

START n=node(3,1,2)
RETURN n
ORDER BY n.name DESC

The example returns the nodes, sorted by their name reversely.

Result

n
0 row
0 ms

(empty result)


Try this query live. (1) {"age":34,"length":170,"name":"A"} (2) {"age":34,"name":"B"} (3) {"age":32,"length":185,"name":"C"} (1)-[:KNOWS]->(2) {} (2)-[:KNOWS]->(3) {} start n=node(3,1,2) return n order by n.name DESC

15.14.4. Ordering null

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.

Query. 

START n=node(3,1,2)
RETURN n.length?, n
ORDER BY n.length?

The nodes are returned sorted by the length property, with a node without that property last.

Result

n.length?n
0 row
0 ms

(empty result)


Try this query live. (1) {"age":34,"length":170,"name":"A"} (2) {"age":34,"name":"B"} (3) {"age":32,"length":185,"name":"C"} (1)-[:KNOWS]->(2) {} (2)-[:KNOWS]->(3) {} start n=node(3,1,2) return n.length?, n order by n.length?