How to Sort Query Results in Salesforce

Sometimes you want to sort query results in ascending or descending order of the value of fields, keep null at the top or bottom etc., To achieve this, the keyword you must know is ORDER BY.

Examples

//This query will arrange the query results alphabetically by First Name

Select Name From Account ORDER BY FirstName

//This query will arrange the query results reverse-alphabetically by Last Name and then in reverse-alphabetically by First Name. If you observe in this query, we can sort based on multiple fields.

Select Name From Account ORDER BY LastName DESC, FirstName DESC

//This query will arrange query results showing null email records first

Select Name From Account ORDER BY Email NULLS FIRST

Note:
You cannot sort results based on Long text area or Multi-Select picklist field or Reference field
SOQL query sorting is case insensitive.
Maximum number of fields based on which you can sort is 32.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s