+ Start a Discussion

Bulk Trigger



I have been looking at the various bulk trigger solutions regarding the "Too many SOQL queries: 101" error.


I'm not sure how to reorganise the following code to get over the SOQL limit as it needs to lookup two fields in a custome object. Would I use a map here? The code works but fails with a larger record set.


Thanks in advance.

trigger targetCompanyDuplicatePreventer on TargetCompany__c (before insert, before update) {

    for (TargetCompany__c tc : System.Trigger.new) {
        // Check if either Account or Target Company List is blank
        if (tc.Account__c == Null || tc.TargetCompanyList__c == Null){
            tc.Account__c.addError('Account or Target Company List cannot be blank. Please select a value.');
        else {
   TargetCompany__c[] duplicateCheck = [select Id from TargetCompany__c where Id != :tc.Id AND Account__c = :tc.Account__c AND TargetCompanyList__c = :tc.TargetCompanyList__c];
   if (duplicateCheck.size() > 0){
    tc.Account__c.addError('Duplicate combination exists. Please enter unique values.');


Yes, maps a are perfect for this.  Whenever you have a select within a loop you're almost certain to hit governor limits.


I can't tell exactly what your code is doing but here's a quick idea of what to do:

Populate a map before your loop.  The map key would possibly be the tc.id and the value would be a set of the id's that are already associated.  Your loop would then test to make sure the "new" id is not already in the set for the incoming insert/update, or something like that...