How can I get results for query on same order as listed on query itself.


(Let's suppose all records with that BackendId__c exist)

SELECT BackendId__c, Name, id FROM Account WHERE BackendId__c IN ('6','2','3','4')
ORDER BY ... ?

Result should be:

BackendId__c Name id
6 John a092p000
2 Mary a092p012
3 Mike a092p031
4 Adam a092p031

1 Answer 1


You can't. The order of query results is undefined if you don't use an explicit ORDER BY clause:

You can use ORDER BY in a SELECT statement to control the order of the query results. There is no guarantee of the order of results unless you use an ORDER BY clause in a query.

ORDER BY sorts by the value of the field, not by the order of specified parameters in the query.

If you need your results ordered in a specific way that does not correspond to sorting by any field in a normal lexicographic/numeric/datewise sort, consider implementing a wrapper class in Apex that implements the Comparable interface to encapsulate your custom logic. You can then call sort() on a list of wrapper objects.

This approach is demonstrated in the documentation, here, with Opportunities, but structurally your solution would be the same.

  • Thanks for you answer. Could you please demonstrate how to use ORDER BY clause, for listed example ?
    – ferret96
    Commented Jul 15, 2019 at 22:58
  • @ferret96 ORDER BY does not apply to your situation, because you do not want the records sorted by the value of a field. If you did ORDER BY BackendId__c, you would get back 2, 3, 4, and 6, in that order.
    – David Reed
    Commented Jul 15, 2019 at 22:59
  • What about using CASE ? I found this, but I'm not sure how to implement it on my example: salesforce.stackexchange.com/questions/53628/…
    – ferret96
    Commented Jul 15, 2019 at 23:03
  • That's a formula field, not a SOQL clause.
    – David Reed
    Commented Jul 15, 2019 at 23:04
  • Thank you for the feedback.
    – ferret96
    Commented Jul 15, 2019 at 23:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .