+ Start a Discussion
Dhanya NDhanya N 

SOQL doesn't return results in the order of list which is used IN: clause

Hi All,

List<Id> pricebookEntryIdList = new List<Id>().
Here I have record ids in the list pricebookEntryIdList which is in the order I want.

List<PricebookEntry> products = [SELECT Id, Product2.Name, Product2.ProductCode, Product2.recordtypeid, Product2.recordtype.name FROM PricebookEntry WHERE Id IN :pricebookEntryIdList]
Above query doesn't return the record details in the same order of pricebookEntryIdList list. 

For example : If pricebookEntryIdList  contains {def, abc, ghi}, products contains records in the order of {abc, def, ghi}

Please help me to solve this.

Thanks,
Dhanya
Dhanya NDhanya N
Hi Ashitha,

I want records to be in the order of pricebookEntryIdList in which I already have Ids in ther order which I want. So ORDER BY Id will not help me here.

Thanks,
Dhanya
v varaprasadv varaprasad
Hi Dhanya,

Please check once below sample code, But this is not a best practice.
 
list<id> idList = new list<id>{'0010I00001fUMmUQAW','0010I00001fUMSFQA4','0010I00001fULmuQAG'};



list<account> anotherlis = new list<account>();
for(id ids : idList){
    account acc = [select id,name from account where id =: ids];
    system.debug('==acc=='+acc);
    anotherlis.add(acc);
}
system.debug('==anotherlis=='+anotherlis);

Above code will work base on record id order it will display records.

 

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For  Support: varaprasad4sfdc@gmail.com



 
Raj VakatiRaj Vakati
Try this code its bulkfied
 
List<Id> pricebookEntryIdList = new List<Id>().

List<PricebookEntry> products = [SELECT Id, Product2.Name, Product2.ProductCode, 
Product2.recordtypeid, Product2.recordtype.name FROM PricebookEntry WHERE Id IN :pricebookEntryIdList]

PricebookEntry[] finalResult = new  PricebookEntry[products.size()];
for(PricebookEntry p : products){
for( Id i : pricebookEntryIdList){
if(p.id==i){
finalResult.set(i , p);
}
}
}

System.debug(finalResult );