Skip to main content

SOQL ORDER BY: Guide to Sorting your Salesforce Queries

SOQL ORDER BY allows you to sort query results efficiently using Salesforce Object Query Language (SOQL).

1. Basic Syntax of SOQL ORDER

The ORDER BY clause is used to sort records based on a specified field in either ascending (ASC) or descending (DESC) order.

Syntax:

SELECT Field1, Field2 FROM ObjectName ORDER BY FieldName ASC | DESC

Example:

SELECT Name, CreatedDate FROM Account ORDER BY CreatedDate DESC

This query retrieves all Account records, sorted by the CreatedDate field in descending order, so the most recently created records appear first.

Sorting by Multiple Fields

You can sort by multiple fields by separating them with commas. If two records have the same value in the first field, SOQL will use the second field to break the tie.

Example:

SELECT Name, Industry, CreatedDate FROM Account ORDER BY Industry ASC, CreatedDate DESC

This query sorts accounts first by Industry in ascending order, and within each industry, by CreatedDate in descending order.

Using NULLS FIRST and NULLS LAST

SOQL allows you to control how NULL values are handled when sorting.

Syntax:

ORDER BY FieldName ASC NULLS FIRST | NULLS LAST
ORDER BY FieldName DESC NULLS FIRST | NULLS LAST

Example:

SELECT Name, Phone FROM Contact ORDER BY Phone ASC NULLS LAST

This query sorts contacts by Phone in ascending order while placing NULL values at the end of the result set.

Limiting Query Results with SOQL ORDER BY

Combining ORDER BY with LIMIT helps retrieve only the top records.

Example:

SELECT Name, AnnualRevenue FROM Account ORDER BY AnnualRevenue DESC LIMIT 10

This retrieves the top 10 accounts with the highest annual revenue.

Performance Considerations

While ORDER BY is useful, sorting large datasets can impact performance. Consider these best practices:

  • Use Indexed Fields: Sorting on indexed fields (like Id, CreatedDate, LastModifiedDate) is faster.
  • Avoid Sorting Large Datasets: Apply filters (WHERE clause) to reduce the number of records before sorting.
  • Optimize Queries with SELECTIVE Queries: Ensure queries remain selective to prevent performance degradation.

SOQL ORDER BY in Relationship Queries

Sorting can be applied in queries that traverse relationships using subqueries.

Example:

SELECT Name, (SELECT LastName FROM Contacts ORDER BY LastName DESC) FROM Account

This retrieves accounts and their associated contacts, sorted by LastName in descending order.

SOQL ORDER BY with Aggregate Queries

When using aggregate functions (GROUP BY), sorting can be done on aggregated fields.

Example:

SELECT Industry, COUNT(Id) FROM Account GROUP BY Industry ORDER BY COUNT(Id) DESC

This groups accounts by industry and sorts them in descending order based on the number of accounts per industry.

We recommend using Workbench to test your SOQL skills

Enjoy this article?

Check out our Master SOQL for Salesforce blog