ORDER BY is a sub-clause following WITH. ORDER BY specifies that the output should be sorted and how it will be sorted.

Introduction

Note that you cannot sort on nodes or relationships, sorting must be done on properties. ORDER BY relies on comparisons to sort the output. See Ordering and comparison of values.

In terms of scope of variables, ORDER BY follows special rules, depending on if the projecting RETURN or WITH clause is either aggregating or DISTINCT. If it is an aggregating or DISTINCT projection, only the variables available in the projection are available. If the projection does not alter the output cardinality (which aggregation and DISTINCT do), variables available from before the projecting clause are also available. When the projection clause shadows already existing variables, only the new variables are available.

Lastly, it is not allowed to use aggregating expressions in the ORDER BY sub-clause if they are not also listed in the projecting clause. This last rule is to make sure that ORDER BY does not change the results, only the order of them.

Order nodes by property

ORDER BY is used to sort the output.

Query

  1. SELECT *
  2. FROM cypher('graph_name', $$
  3. MATCH (n)
  4. WITH n.name as name, n.age as age
  5. ORDER BY n.name
  6. RETURN name, age
  7. $$) as (name agtype, age agtype);

The nodes are returned, sorted by their name.

Result

name age
“A” 34
“B” 34
“C” 32
(1 row)

Order nodes by multiple properties

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

Query

  1. SELECT *
  2. FROM cypher('graph_name', $$
  3. MATCH (n)
  4. WITH n.name as name, n.age as age
  5. ORDER BY n.age, n.name
  6. RETURN name, age
  7. $$) as (name agtype, age agtype);

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

Result

name age
“C” 32
“A” 34
“B” 34
(1 row)

Order nodes in descending order

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

Query

  1. SELECT *
  2. FROM cypher('graph_name', $$
  3. MATCH (n)
  4. WITH n.name AS name, n.age AS age
  5. ORDER BY n.name DESC
  6. RETURN name, age
  7. $$) as (name agtype, age agtype);

The example returns the nodes, sorted by their name in reverse order.

Result

name age
“C” 32
“B” 34
“A” 34
(3 rows)

Ordering null

When sorting the result set, null will always come at the end of the result set for ascending sorting, and first for descending sorting.

Query

  1. SELECT *
  2. FROM cypher('graph_name', $$
  3. MATCH (n)
  4. WITH n.name AS name, n.age AS age, n.height
  5. ORDER BY n.height
  6. RETURN name, age, height
  7. $$) as (name agtype, age agtype, height agtype);

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

Result

name age
“A” 34 170
“C” 32 185
“B” 34 <NULL>
(3 rows)