Prev |  | Next

## 15.14. 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.

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
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.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
3 rows
0 ms
`Node[3]{name:"C",age:32,length:185}`
`Node[1]{name:"A",age:34,length:170}`
`Node[2]{name:"B",age:34}`

### 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
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.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
--- | ---
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}`

Copyright © 2013 Neo Technology

Prev | Up | Next
| Home |