9.2. Order by

To sort the output, use the ORDER BY clause. 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”.

Figure 9.2. Graph

Order nodes by property

ORDER BY is used to sort the output.

Query 

MATCH (n)
RETURN n
ORDER BY n.name

The nodes are returned, sorted by their name.

Result

n
3 rows

Node[0]{name:"A",age:34,length:170}

Node[1]{name:"B",age:34}

Node[2]{name:"C",age:32,length:185}

Try this query live create (_0 {`age`:34, `length`:170, `name`:"A"}) create (_1 {`age`:34, `name`:"B"}) create (_2 {`age`:32, `length`:185, `name`:"C"}) create _0-[:`KNOWS`]->_1 create _1-[:`KNOWS`]->_2 match (n) return n order by n.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.

Query 

MATCH (n)
RETURN n
ORDER BY n.age, n.name

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

Result

n
3 rows

Node[2]{name:"C",age:32,length:185}

Node[0]{name:"A",age:34,length:170}

Node[1]{name:"B",age:34}

Try this query live create (_0 {`age`:34, `length`:170, `name`:"A"}) create (_1 {`age`:34, `name`:"B"}) create (_2 {`age`:32, `length`:185, `name`:"C"}) create _0-[:`KNOWS`]->_1 create _1-[:`KNOWS`]->_2 match (n) return n order by n.age, n.name

Order nodes in descending order

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

Query 

MATCH (n)
RETURN n
ORDER BY n.name DESC

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

Result

n
3 rows

Node[2]{name:"C",age:32,length:185}

Node[1]{name:"B",age:34}

Node[0]{name:"A",age:34,length:170}

Try this query live create (_0 {`age`:34, `length`:170, `name`:"A"}) create (_1 {`age`:34, `name`:"B"}) create (_2 {`age`:32, `length`:185, `name`:"C"}) create _0-[:`KNOWS`]->_1 create _1-[:`KNOWS`]->_2 match (n) return n order by n.name DESC

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 

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.

Result

n.lengthn
3 rows

170

Node[0]{name:"A",age:34,length:170}

185

Node[2]{name:"C",age:32,length:185}

<null>

Node[1]{name:"B",age:34}

Try this query live create (_0 {`age`:34, `length`:170, `name`:"A"}) create (_1 {`age`:34, `name`:"B"}) create (_2 {`age`:32, `length`:185, `name`:"C"}) create _0-[:`KNOWS`]->_1 create _1-[:`KNOWS`]->_2 match (n) return n.length, n order by n.length