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
Sudhir PandaSudhir Panda 

To avoid SOQL's in the for loop

for(String line:lines){
                if(cnt!=0 && Util.IfNull(line)!=''){
                    try{
                        fields = line.split(',', -1);
                        message = fields[1];
                        temp = fields[3].normalizeSpace();// remove white space
                        temp = temp.replace('\\n\\r', '');// remove CRLF
                        system.debug('temp:'+temp);
                        
                        giverId = [Select id from User where Alias =: Util.IfNull(fields[0]) limit 1].Id;
                        receiverId = [Select id from User where Alias =: Util.IfNull(fields[2]) limit 1].Id;
                        badgeId = [SELECT Id FROM WorkBadgeDefinition where Name =: temp limit 1].Id;

Hi,
Is there any way we could avoid those DML's and use before the for loop for the giverId, recieverId, badgeId. As it leads to :- Too many SOQL queries: 101
ANUTEJANUTEJ (Salesforce Developers) 
Hi Sudhir,

We find that in your code you are having the soql queries in the foe loop and iterating through the for loop so that is the reason we see the soql queries:101 error. I think you can run the for loop and store the values in 3 seperate sets then you can have a condition that says if the values are in sets then fetch the records.

I hope the above way helps and in case if it does, can you please choose this as the best answer so that it can be used by others in the future.

Regards,
Anutej