function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
UdayWagle20UdayWagle20 

SOQL does not return results in the same order of list used in IN: clause

Hi All,

Here I have list of account Ids.
List<Id> accIds= new List<Id>()

List<Contact> conList = [SELECT Id,Name WHERE accountId IN :accIds];

Now in the above conList I want to query the contacts in same order as the ids in the account.

currently what is happening is if accIds list contain {1,2,3}, contacts are returned in the order {2,1,3}

I want them to be in the same order.

How do I achive this ? Please help me to resolve the above issue.

ANUTEJANUTEJ (Salesforce Developers) 
Hi Uday,

Can you try using the ORDER BY on a field and see if it works?

Regards,
Anutej
UdayWagle20UdayWagle20

Thanks for the reply Anutej.

I have tried it, it won't work for my usecase. Want to know how  it can be done for the above use case with the list of ids in the IN: clause.

 

Regards,

Uday
ANUTEJANUTEJ (Salesforce Developers) 
Oh, to my knowledge I don't think the order in which the records are returned is not constant however I think you could run a loop to reorder the records in the list.
UdayWagle20UdayWagle20
got it, Thanks a lot Anutej.
ANUTEJANUTEJ (Salesforce Developers) 
Glad to know it helped.