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
Name | StageName | Probability | ExpectedRevenue |
---|---|---|---|
Apple Inc | Negotiation/Review | 90 | 235.521 |
Dickenson Mobile Generators | Qualification | 10 | 1500 |
Big Corp | Negotiation/Review | 90 | 5694.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
Name | StageName | Probability | ExpectedRevenue |
---|---|---|---|
Big Corp | Negotiation/Review | 90 | 5694.129 |
Dickenson Mobile Generators | Qualification | 10 | 1500 |
Apple Inc | Negotiation/Review | 90 | 235.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
Name | StageName | Probability | ExpectedRevenue |
---|---|---|---|
United Oil Installations | Negotiation/Review | 90 | 243000 |
United Oil Office Portable Generators | Negotiation/Review | 90 | 112500 |
Bill's Sports & Outdoors | Negotiation/Review | 90 | 81327.15 |
... | ... | ... | ... |
Multi-select picklist, rich text area, long text area, encrypted, and data category group reference (for Salesforce Knowledge) can not be ordered.