SOQL ORDER BY

The ORDER BY clause is used to sort the returned rows in the specified order. We can sort ascending or descending by specifying ASC or DESC keyword.

If we do not specify anything, ascending order is used. We con sort multiple fields at the same time, and the sorting order is left to right.

We can sort text, number, date, datetime and text fields.

Example #1: Find all the clinics in descending order of their name.

SELECT Id, Name
FROM Clinic__c
ORDER BY Name DESC

Example #2: Find all the clinics in various states and cities and sort them first by states, and then by cities.

SELECT Id, Name
FROM Clinic__c
ORDER BY state__c, city__c

You can also sort based on an aggregated field in GROUP BY clause.

Example #3: Find the clinics and their total booking amount in the previous month. Sort the results in descending order of the total booking amount.

SELECT Sum(Booking_Amount__c), Clinic__c
FROM Appointment__c
GROUP BY Clinic__c
ORDER BY Sum(Booking_Amount__c) DESC
TIPS
You can sort by ascending and descending in different fields in the same query.