+ Start a Discussion
Div403Div403 

How to avoid query in inside for loop?

trigger DuplicateAccountNameCountryCheck1 on Account (before insert, before update)
{
    For(Account a:Trigger.New)
    {
        List<Account> acc=[SELECT Id, Name FROM Account WHERE Name=:a.Name AND BillingCountry=:a.BillingCountry];
        if(acc.size()>0)
        {
            a.addError('You are not allow to create duplicate Account Name with the same Country');
        } 
    }
}
Best Answer chosen by Div403
RamuRamu (Salesforce Developers) 
You can create a map to avoid queries inside for loop. Try out the below code and let me know if it worked
 
trigger DuplicateAccountNameCountryCheck1 on Account (before insert, before update)
{
map<string,string> accdb=new map<string,string>();
List<Account> acc=new list<Account>([SELECT Name,billingcountry FROM Account]);
	for(Account ac:acc){
	accdb.put(ac.name,ac.billingcountry);
	}

    For(Account a:Trigger.New)
    {
        if(accdb.containskey(a.name) && a.billingcountry==accdb.get(a.name))
        {
            a.adderror("you cannot add duplicate account with the same name and billing country");
        } 
    }
}

 

All Answers

RamuRamu (Salesforce Developers) 
You can create a map to avoid queries inside for loop. Try out the below code and let me know if it worked
 
trigger DuplicateAccountNameCountryCheck1 on Account (before insert, before update)
{
map<string,string> accdb=new map<string,string>();
List<Account> acc=new list<Account>([SELECT Name,billingcountry FROM Account]);
	for(Account ac:acc){
	accdb.put(ac.name,ac.billingcountry);
	}

    For(Account a:Trigger.New)
    {
        if(accdb.containskey(a.name) && a.billingcountry==accdb.get(a.name))
        {
            a.adderror("you cannot add duplicate account with the same name and billing country");
        } 
    }
}

 
This was selected as the best answer
Div403Div403
Thanks Ramu for your quick response

But, I am facing the below error 

execution of BeforeUpdate caused by: System.StringException: Invalid id: US
 
Div403Div403
Its working fine now. Thank you very much