You need to sign in to do that
Don't have an account?
Manjunath
Removing SOQL from for loop.
Hi,
As per salesforce's best practice for writing trigger. It suggests to avoid SOQL inside the for loop, but there might be some scenarios where in we need to use SOQL inside. How to Avoid this?
Regards,
for(Contact c : contacts)
//add c.AccountId in a Set
//Fetch Account data using set and add it in map
Map<Id, Account> mapAccounts = [Select Id, Name from Account where Id In set];
//now use this map for getting account data
Hi,
The example you have giving is again using SOQL in for loop. How to avoid that. As in my knowledge, if we add 200 contacts to the given example then this will hit governor limit.
(I was planning to give the same example :))
Regards
looks like, you took it in wrong way :). This is what i was explaining:
Hi,
Cool This work fine for the given scenario.
How about for this one that I just made up. I thought posting the code will give more info than explaining.
Regards,
Just below the Account query, create one more query:
List<Contact> contacts = [Select Id from Contact where Department in DeppartmentSet];
//loop through these records and create a Map of Contacts with department
Map<Department, List<Contact>> mapContactDeps ;4
Use this map for futher processing
Hi Manhunath,
use below trigger i think it will work fine for your scenario.
Apex trigger:
Important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.
Thanks,
Hitesh Patel
Hi Tech Force,
This sounds good, but there might be a case where for a Department='1' it might return more than 200 records. Then it might again hit governor limit right?
Thanks for your replies.
Regards,
That's why we are using Map<String, List<Contact>>, So if there are N number of contacts for a department, then it would be able to manage.
Thanks for taking interest in replying .
Hi,
I feel that in certain scenarios you cannot avoid SOQL inside for loop.
What is your view Tech Force and Jerun Jose ?
Regards,
From my experience, you can always avoid using a query inside a for loop by using a proper code design and usage of collections.
For removing SOQL from the loop you can use Map, With the help of Map you can easily avoid SOQL
from inside the loop.
If you find your Solution then mark this as the best answer.
Thank you!
Regards
Suraj Tripathi