15

I'm looking for a way to achieve this in SOQL:

https://stackoverflow.com/questions/8532599/need-to-perform-order-by-twice

I'd like to order by the Priority field on Case, otherwise order by Age of Case

So for example:

Priority - Age of Case

Urgent , 5
Urgent , 4
High   , 7
High   , 6
Low    , 17
Low    , 10
Low    , 5

Hope this makes sense.

2
  • 20 seconds after posting I found the syntax is ORDER BY Field1, Field2. Accepted answer goes to first who posts a link to the documentation where this is detailed
    – user24634
    Commented Nov 2, 2016 at 14:54
  • 2
    SELECT Priority , Age of Case FROM Case ORDER BY Priority ASC, Age of Case DESC ? "Multiple column sorting is supported, by listing more than one fieldExpression clause." As per documentation developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/… Commented Nov 2, 2016 at 14:57

2 Answers 2

28

You need to separate fields with comma like this :

ORDER BY YOURFIELD1, YOURFIELD2

See the documentation : http://developer.force.com/cookbook/recipe/sorting-query-results

0
10

Since Priority is type text, you could not order in a way explained. It would order alphabetically.

e.g., High -> Low -> Urgent (Alphabetically)

So, you could create one more field that is numeric and can be sorted.

Priority: 1 (Urgent), 2 (High), 3 (Low)

Then you could write SOQL like:

SELECT Priority__c, Priority_Number__c, Age__c FROM Object__c ORDER BY Priority_Number__c ASC, Age__c ASC
1
  • Thanks San. It's an ordered pick-list so in my case it works, but you make a good point! +1
    – user24634
    Commented Nov 2, 2016 at 14:59

You must log in to answer this question.