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
MATCH(n:Movie)
WHERE n.genre="comedy"
RETURN n.title
ORDER BY id(n) DESC
- Sort nodes in descending order Cypher query neo4j
- Get all nodes cypher query neo4j
- Get all nodes with same label using label name Cypher query neo4j
- Get all related nodes of a node using Cypher query neo4j
- Get nodes using multiple ids Cypher query neo4j
- Create one or multiple nodes Cypher query neo4j
- Delete nodes using Cypher query neo4j