Basics
SOQL ORDER BY
Sorting Results
SOQL ORDER BY sorts results with ASC or DESC modifiers.
Introduction to SOQL ORDER BY
The ORDER BY clause in SOQL (Salesforce Object Query Language) is used to sort the results of a query in either ascending or descending order. This is particularly useful when you need to organize data in a specific sequence for better readability and data manipulation.
Syntax of ORDER BY Clause
The basic syntax of the ORDER BY clause in SOQL is:
SELECT fieldList FROM objectType ORDER BY field ASC|DESCHere, fieldList refers to the fields you want to retrieve, objectType is the object you're querying, and field is the field by which you want to sort.
Using ASC and DESC Modifiers
By default, if no modifier is specified, SOQL sorts results in ascending order (ASC). If you want to sort in descending order, you can use the DESC keyword.
In this example, the query retrieves account names and their creation dates, sorting the results by the CreatedDate in ascending order.
This query retrieves account names and their annual revenues, sorting the results by AnnualRevenue in descending order.
Ordering by Multiple Fields
You can also order results by multiple fields. When doing so, the query sorts based on the first field. If there are identical values, it will then sort by the second field, and so on.
In this case, accounts are first sorted by Industry. Within each industry, they are further sorted by AnnualRevenue in descending order.
Handling NULL Values in ORDER BY
SOQL treats NULL values as the lowest values. When ordering in ascending order, NULL values appear first; when ordering in descending order, they appear last.
This query sorts contacts by their LastActivityDate in descending order, meaning contacts with NULL activity dates will appear at the end of the list.
Best Practices for Using ORDER BY
- Use indexed fields for ordering to improve query performance.
- Limit the number of fields you order by to reduce complexity.
- Always specify ASCorDESCfor clarity.
