Newer Version Available

This content describes an older version of this product. View Latest

ORDER BY

You can use ORDER BY in a SELECT statement to control the order of the query results. There is no guarantee of the order of results unless you use an ORDER BY clause in a query. The syntax is:

1[ORDER BY fieldExpression ASC | DESC ? NULLS FIRST | LAST ?]
Syntax Description
ASC or DESC Specifies whether the results are ordered in ascending (ASC) or descending (DESC) order. Default order is ascending.
NULLS FIRST or NULLS LAST Orders null records at the beginning (NULLS FIRST) or end (NULLS LAST) of the results. By default, null values are sorted first.

For example, the following query returns a query result with Account records in alphabetical order by first name, sorted in descending order, with accounts that have null names appearing last:

1SELECT Name
2FROM Account
3ORDER BY Name DESC NULLS LAST

The following factors affect results returned with ORDER BY:

  • Sorting is case insensitive.
  • ORDER BY is compatible with relationship query syntax.
  • Multiple column sorting is supported, by listing more than one fieldExpression clause.
  • Relationship queries with foreign key values in an ORDER BY clause behave differently depending on the version of the Force.com API. In an ORDER BY clause, if the foreign key value in a record is null, the record is returned in version 13.0 and later, but not returned in versions before 13.0.
    1SELECT Id, CaseNumber, Account.Id, Account.Name
    2FROM Case
    3ORDER BY Account.Name
    Any case record for which AccountId is empty is returned in version 13.0 and later.
  • Sort order is determined by current user locale. For English locales, Salesforce uses a sorting mechanism based on the UTF-8 values of the character data. For Asian locales, Salesforce uses a linguistic sorting mechanism based on the ISO 14651 and Unicode 3.2 standards.

The following limitations apply to data types when using ORDER BY:

  • These data types are not supported: multi-select picklist, rich text area, long text area, encrypted (if enabled), and data category group reference (if Salesforce Knowledge is enabled).
  • All other data types are supported, with the following caveats:
    • convertCurrency() always sorts using corporate currency value, if available.
    • phone data does not include any special formatting when sorting, for example, non-numeric characters such as dash or parentheses are included in the sorting.
    • picklist sorting is defined by the picklist sort determined during setup.

You can use ORDER BY with the optional LIMIT qualifier, in a SELECT statement:

1SELECT Name
2FROM Account
3WHERE industry = 'media'
4ORDER BY BillingPostalCode ASC NULLS LAST LIMIT 125

You are limited to 32 fields in an ORDER BY query. If you exceed the limit, a malformed query fault is returned.