Order By
Not Started

Let's add a little order to things.

With the SOQL statements we've seen so far, there is no guarantee that re-running the query will return the results in the same order.

Say you need to find the open Opportunities in the system with the lowest expected revenue. With what we know so far, the closest we can get is:

SELECT Name, StageName, Probability, ExpectedRevenue FROM Opportunity WHERE IsClosed = false

Ordering the query results allows us to get exactly what we want. The optional ORDER BY clause is used after the SELECT, FROM, and WHERE clauses. It can be used to apply 🔼 ascending or 🔽 descending sorting to the fields we specify. If you don't specify the sort order, the statement will implicitly sort in ascending order.

ASC is the keyword for ascending order. DESC is the keyword for descending order. Let's update our SOQL to order the results by the expected revenue.

SELECT Name, StageName, Probability, ExpectedRevenue FROM Opportunity WHERE IsClosed = false ORDER BY ExpectedRevenue ASC

NameStageNameProbabilityExpectedRevenue
Apple IncNegotiation/Review90235.521
Dickenson Mobile GeneratorsQualification101500
Big CorpNegotiation/Review905694.129
............

If instead, we wanted to see the Opportunities with the highest Expected Revenue first followed by those with smaller values, we would write:

SELECT Name, StageName, Probability, ExpectedRevenue FROM Opportunity WHERE IsClosed = false ORDER BY ExpectedRevenue DESC



NameStageNameProbabilityExpectedRevenue
Big CorpNegotiation/Review905694.129
Dickenson Mobile GeneratorsQualification101500
Apple IncNegotiation/Review90235.521
............



To add a few more fields to ORDER BY, we specify them in a comma-separated , list. Here we see the open Opportunities, with the highest probability, and highest revenue first in the list.

SELECT Name, StageName, Probability, ExpectedRevenue FROM Opportunity WHERE IsClosed = false ORDER BY Probability DESC, ExpectedRevenue DESC

NameStageNameProbabilityExpectedRevenue
United Oil InstallationsNegotiation/Review90243000
United Oil Office Portable GeneratorsNegotiation/Review90112500
Bill's Sports & OutdoorsNegotiation/Review9081327.15
............

Multi-select picklist, rich text area, long text area, encrypted, and data category group reference (for Salesforce Knowledge) can not be ordered.

Challenge

Write a query that returns the Name, Rating, and Number of Employees for each Account whose rating is Cold. Order results so that the Account with the highest number of employees shows up first.