Neo4j CQL - Sorting



Neo4j CQL ORDER BY clause

Neo4j CQL has provided "ORDER BY" Clause in MATCH Command to sort the results returned by a MATCH query.

We can sort rows either ascending order or descending order.

By default, it sorts rows in ascending order. If we want to sort them in descending order, we need to use DESC clause

ORDER BY clause syntax

ORDER BY  <property-name-list>  [DESC]	
S.No.Syntax ElementDescription
1.ORDER BYIt is a Neo4j CQL keyword.
2.<property-name-list>It is a list of properties used in sorting.
3.DESCIt is a Neo4j CQL keyword used to specify descending order.It is optional.

<property-name-list> syntax:

<node-label-name>.<property1-name>,
<node-label-name>.<property2-name>, 
.... 
<node-label-name>.<propertyn-name> 

Syntax Description

S.No.Syntax ElementDescription
1.<node-label-name>It is a label name of a Node.
2.<property-name>It is a property name of a Node.

NOTE -

We should use comma(,) operator to separate the property names list.

Example

This example demonstrates how to use sort results in Ascending order by Employee name.

Step 1 - Open Neo4j Data Browser

Neo4j CQL Tutorial

Step 2 - Type the below command on Data Browser

MATCH (emp:Employee)
RETURN emp.empid,emp.name,emp.salary,emp.deptno
Neo4j CQL Tutorial

Step 3 - Click on "Execute" button and observe the results.

Neo4j CQL Tutorial

It returns total number of results available in the database: 4 records

Step 4 - Type the below command on Data Browser

MATCH (emp:Employee)
RETURN emp.empid,emp.name,emp.salary,emp.deptno
ORDER BY emp.name
Neo4j CQL Tutorial

Step 5 - Click on "Execute" button and observe the results.

Neo4j CQL Tutorial

If we observe the results, now records are sorted by Employee.name in ascending order.

Example

This example demonstrates how to use sort results in Descending order by Employee name.

Step 1 - Open Neo4j Data Browser

Step 2 - Type the below command on Data Browser

MATCH (emp:Employee)
RETURN emp.empid,emp.name,emp.salary,emp.deptno
Neo4j CQL Tutorial

Step 3 - Click on "Execute" button and observe the results.

Neo4j CQL Tutorial

It returns total number of results available in the database: 4 records

Step 4 - Type the below command on Data Browser

MATCH (emp:Employee)
RETURN emp.empid,emp.name,emp.salary,emp.deptno
ORDER BY emp.name DESC
Neo4j CQL Tutorial

Step 5 - Click on "Execute" button and observe the results.

Neo4j CQL Tutorial

If we observe the results, now records are sorted by Employee.name in Descending order.

Advertisements