The ORDER BY statement allows you to sort the intermediate result or output table based on the specified columns.
Syntax<order by statement> ::= "ORDER BY" <sort specification> [ { "," <sort specification> }... ] <sort specification> ::= <value expression> [ "ASC" | "DESC" ] [ "NULLS FIRST" | "NULLS LAST" ]
Details
ASC (ascending) is applied by default. To reverse the order, you can explicitly use the DESC (descending) keyword.NULLS FIRST and NULLS LAST can be used to control whether null values appear before or after non-null values. When null ordering is not explicitly specified:
NULLS LAST is applied by default when ordering in the ASC order.NULLS FIRST is applied by default when ordering in the DESC order.
CREATE GRAPH myGraph { NODE Paper ({title string, score uint32, author string, publisher string}), EDGE Cites ()-[{weight uint32}]->() } PARTITION BY HASH(Crc32) SHARDS [1]
GQLMATCH (n:Paper) ORDER BY n.score RETURN n.title, n.score
Result:
| n.title | n.score |
|---|---|
| Efficient Graph Search | 6 |
| Path Patterns | 7 |
| Optimizing Queries | 9 |
When a node or edge variable is specified, it is sorted on the _uuid of the nodes or edges.
GQLMATCH (n:Paper) RETURN n.title, element_id(n) ORDER BY n
Result:
| n.title | element_id(n) |
|---|---|
| Optimizing Queries | 8718971077612535810 |
| Efficient Graph Search | 8791028671650463745 |
| Path Patterns | 12033620403357220867 |
GQLMATCH p = (:Paper)->{1,2}(:Paper) RETURN p, path_length(p) AS length ORDER BY length DESC
Result:
| p | length |
|---|---|
![]() | 2 |
![]() | 1 |
![]() | 1 |
When there are multiple specifications, it is sorted by the first specification listed, and for equals values, go to the next specification, and so on.
GQLMATCH (n:Paper) RETURN n.title, n.author, n.score ORDER BY n.author DESC, n.score
Result:
| n.title | n.author | n.score |
|---|---|---|
| Path Patterns | Zack | 7 |
| Efficient Graph Search | Alex | 6 |
| Optimizing Queries | Alex | 9 |
You may use the SKIP or LIMIT statement after the ORDER BY statement to skip a specified number of records from the top, or to limit the number of records retained.
To return titles of the two papers with the second and third highest scores:
GQLMATCH (n:Paper) RETURN n.title, n.score ORDER BY n.score DESC SKIP 1 LIMIT 2
Result:
| n.title | n.score |
|---|---|
| Path Patterns | 7 |
| Efficient Graph Search | 6 |
To return titles of the two papers with the second and third highest scores, ensuring null values appear at the front if applicable:
GQLMATCH (n:Paper) RETURN n.title, n.publisher ORDER BY n.publisher NULLS FIRST
Result:
| n.title | n.score |
|---|---|
| Optimizing Queries | null |
| Path Patterns | BrightLeaf |
| Efficient Graph Search | PulsePress |