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
Mahendiran Jayavarma 24Mahendiran Jayavarma 24 

How to avoid SOQL inside for loop

Hi, I am getting error and seend SOQL Queries Inside FOR Loops. How to avaoid this. 

  private static void setOwnerToBrandAdmin(List<Contact> newContacts) {
        List<Id> contactIds = new List<Id>();
        for (Contact newContact : newContacts) {
            contactIds.add(newContact.Id);
        }

        
        List<Contact> contacts = [SELECT Id, Brand__c, OwnerId, Owner.Name FROM Contact WHERE Id IN :contactIds];
        List<Contact> contactsToUpdate = new List<Contact>();       
       
        for (Contact contact : contacts) {
            if (contact.Owner.Name == 'Integration') {                
       
                List<Brand_Admin__c> admins = [SELECT User__c FROM Brand_Admin__c WHERE Brand__c = :contact.Brand__c];
                if(admins.size() > 0) {
                    contact.OwnerId = admins[0].User__c;
                    contactsToUpdate.add(contact);
                }
            }
        }

        update contactsToUpdate;
    }
AnudeepAnudeep (Salesforce Developers) 
private static void setOwnerToBrandAdmin(List<Contact> newContacts) {
        List<Id> contactIds = new List<Id>();
        List<String> brands = new List<String>();
        for (Contact newContact : newContacts) {
            contactIds.add(newContact.Id);
            brands.add(newContact.brand__c);

        }

        
        List<Brand_Admin__c> admins = [SELECT User__c FROM Brand_Admin__c WHERE Brand__c IN:brands];

        List<Contact> contacts = [SELECT Id, Brand__c, OwnerId, Owner.Name FROM Contact WHERE Id IN :contactIds];
        List<Contact> contactsToUpdate = new List<Contact>();       
       
        for (Contact contact : contacts) {
            if (contact.Owner.Name == 'Integration') {                
                       if(admins.size() > 0) {
                    contact.OwnerId = admins[0].User__c;
                    contactsToUpdate.add(contact);
                }
            }
        }

        update contactsToUpdate;
    }

Let me know if this gives you the same output