How to sort SOQL with 2 fields?

596    Asked by DianeCarr in Salesforce , Asked on Aug 28, 2023

If I have to make a SOQL Query with the animals sorted by CreatedDate DESC and Zoo Id, wherein I have object Animal__c and field ZooId, then how can I sort this using SOQL orderby instead of using GROUP BY? My target result is:

Animal 3 ZooId 5 CreatedDate Today
Animal 0 ZooId 5 CreatedDate Yesterday
Animal 4 ZooId 5 CreatedDate Yesterday
Animal 1 ZooId 4 CreatedDate Today
Animal 2 ZooId 4 CreatedDate Yesterday

Answered by dia shrinidhi

 I understand that in the SOQL & SOSL documentation, anything ordered by multiple columns is listed in ORDER BY.

Certain factors can affect the results returned with ORDER BY- whether sorting is case insensitive if the ORDER BY is compatible with relationship query syntax. Lastly, Multiple-column sorting is supported by listing more than one field expression clause. The central part here is to decide the order in which you need to do the sorting. Another critical point to remember is that the frequency at which the sorted fields change in our result depends on the order in which they were sorted. Hence, we can say that the first things to change will have the lowest frequency, and the last will have the highest.

In your case, the solution can be as follows:

ZooId transitions once (5 -> 4), whereas CreatedDate transitions 3 times (Today -> Yesterday, Yesterday -> Today, Today -> Yesterday).
Therefore, ZooId must be sorted first, and CreatedDate must be sorted second.

Your Answer

Interviews

Parent Categories