Prev |  | Next

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

Graph

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

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

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

### 16.8.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.length | n
--- | ---
3 rows, 1 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 © 2011 Neo Technology

Prev | Up | Next
| Home |