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
Dejan CvetkoskiDejan Cvetkoski 

Optimize SOQL Query

Hi people, i need help:

I have map of list and that map it's very big, for every key i have list and i execute query for that list.
Map<String,List<String>> map = new Map<string,List<String>>();
for(String key : map.keySet()){
    List<Sobject>  lsit = [SELECT Id, Name, Code FROM Sobject WHERE Name in map.get(key)] ;
}
How i can optimize this, if have way for execute in one query all that, how i can execute multiple list in query? This is important for me!
Thanks.
 
Alexander TsitsuraAlexander Tsitsura
Hi Dejan,

You need avoid soql for loop. See code below
 
Map<String,List<String>> map = new Map<string,List<String>>();
Set<String> names = new Set<String>();
for (String key : map.keySet()) {
    names.addAll(map.get(key));
}

Map<String, Account> accountsMap  new Map<String> Account>();
for(Account a : [SELECT Id, Name, Code FROM Sobject WHERE Name in :names] ) {
  accountsMap.put(a.Name, a);
}

for(String key : map.keySet()){
    List<Account> accountsList = new List<Account>();
    for (String name : map.get(key)) {
        if (accountsMap.containsKey(name)) {
            accountsList.add(accountsMap.get(name));
        }
    }

    // logic here

}

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Thanks,
Alex
 
Dejan CvetkoskiDejan Cvetkoski
I nedd put in query List<List<String>> or Map<String,List<String>> and execute in one query is that Is it possible?
Thanks
Abhishek BansalAbhishek Bansal
Hi Dejan,

You can use the below code to avoid SOQL in loop.
Please change your code according to the below script :
Map<String,List<String>> map = new Map<string,List<String>>();
Set<String> allListValues = new Set<String>();
for(String key : map.keySet()){
	allListValues.addAll(map.get(key));
}
List<Sobject>  lsit = [SELECT Id, Name, Code FROM Sobject WHERE Name in : allListValues];
Let me know if there is any issue.

Thanks,
Abhishek