8

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.

  • 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 Nov 2 '16 at 14:54
  • 1
    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/… – Simon Govaert Nov 2 '16 at 14:57
16

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

|improve this answer|||||
  • 1
    That's not documentation, and it's SQL – Adrian Larson Nov 2 '16 at 14:57
  • 2
    Yes I copied the wrong link ! I edited – SF_user Nov 2 '16 at 14:58
7

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
|improve this answer|||||
  • Thanks San. It's an ordered pick-list so in my case it works, but you make a good point! +1 – user24634 Nov 2 '16 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy