neo4j

Sort nodes by id ascending and descending order neo4j Cypher query

To sort records or nodes by id, the id() method can be used with the order by clause. By default, the records will be sorted in ascending order. To sort the records in descending order, the DESC keyword is used.

//Sort in ascending order
MATCH (n)
RETURN n.fullname, n.email
ORDER BY id(n)

//Sort in descending order
MATCH (n)
RETURN n.fullname, n.email
ORDER BY id(n) DESC

Every node in the neo4j graph database has a unique id by default. It starts from 0 by default and if we want to sort the nodes based on this id, we can use the id() method in our Cypher query.

In the above Cypher query, we are sorting nodes by their id and returning fullname and email property values of nodes. By default when we use the ORDER BY clause with the id(n) method to sort nodes by id, it will sort the record in ascending order. We are using the DESC keyword with the ORDER BY clause to sort the records in descending order. 

The basic syntax of Cypher query to sort nodes by their default unique id is as below:

MATCH (n)
RETURN n
ORDER BY id(n)
//Ascending order
MATCH (n:Person)
RETURN n.username, n.email
ORDER BY id(n)

//Descending order
MATCH (n:Person)
RETURN n.username, n.email
ORDER BY id(n) DESC
The above Cypher query will sort the nodes that have Person labels associated with them using node unique id in ascending and descending order.
MATCH(n:Movie)
WHERE n.genre="comedy"
RETURN n.title
ORDER BY id(n) DESC
In the above Cypher query, we are filtering nodes that have Movie label and genre property of nodes containing value Comedy. Then we are Ordering them using ORDER BY keywords with the id(n) function.
Was this helpful?