15.9. Order by

15.9.1. Order nodes by property
15.9.2. Order nodes by multiple properties
15.9.3. Order nodes in descending order
15.9.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.

Graph

cypher-orderby-graph.svg

15.9.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, sorted by their name.

Result

n
3 rows, 0 ms

Node[1]{name->"A",age->34,length->170}

Node[2]{name->"B",age->34}

Node[3]{name->"C",age->32,length->185}


15.9.2. Order nodes by multiple properties

You can order by multiple properties by stating each identifier in the ORDER BY statement. Cypher will sort the result by the first identifier listed, and for equals values, go to the next property in the order by, and so on.

Query

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

The nodes, sorted first by their age, and then by their name.

Result

n
3 rows, 1 ms

Node[3]{name->"C",age->32,length->185}

Node[1]{name->"A",age->34,length->170}

Node[2]{name->"B",age->34}


15.9.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 nodes, sorted by their name reversely.

Result

n
3 rows, 0 ms

Node[3]{name->"C",age->32,length->185}

Node[2]{name->"B",age->34}

Node[1]{name->"A",age->34,length->170}


15.9.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 sorted by the length property, with a node without that property last.

Result

n.lengthn
3 rows, 0 ms

170

Node[1]{name->"A",age->34,length->170}

185

Node[3]{name->"C",age->32,length->185}

<null>

Node[2]{name->"B",age->34}