[SalesForce] SOQL SORTING WITH 2 FIELDS

I have the object Animal__c, with the field ZooId.

I want to make an SOQL Query with the animals sorted by CreatedDate DESC and Zoo Id.

Now the list is:

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

SELECT Id, CreatedDate, ZooId ORDER BY CreatedDate DESC, ZooId

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

And I want this:

  • 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

Is that possible?? Sorting like this With an SOQL Query?? Without using GROUP BY because I am not interested in aggregate results. My priority is
**

  • first sorting by CreatingDate.
  • second sorting by ZooId.

**

Best Answer

Generally speaking, when I have a question, the first place I look is at the documentation.

Ordering by multiple columns is listed in ORDER BY in the SOQL & SOSL documentation (emphasis mine)

The following factors affect results returned with ORDER BY:

  • Sorting is case insensitive.
  • ORDER BY is compatible with relationship query syntax.
  • Multiple column sorting is supported, by listing more than one fieldExpression clause.

I don't think there's anything in the documentation that explicitly says that you can specify a different sort order per field, but it is indeed possible.

ex. [SELECT Id, Name, Site, CreatedDate FROM Account ORDER BY Site DESC NULLS LAST, CreatedDate ASC LIMIT 100]

Beyond that, the key here is to realize the order in which you need to do the sorting.

The sorting is applied from the leftmost statement, and proceeds right. The end effect is that the frequency at which the sorted fields change in your result also depends on the order in which they were sorted. The first thing that's sorted has the lowest frequency of change in the sorted result, and the last thing that is sorted will (can is probably a better word here) have the highest frequency of change.

Given your target result

  • 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

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

Related Topic