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

Too many SOQL queries

I think the issue is the SOQL in the for statement, but I'm having issues trying to put this kind of SOQL Count in a map. I'm assuming some sort of mapping is required to get around my too many queries issue.


Can someone please point me in the right direction?



trigger StarRatingCampaign on CampaignMember (after insert)
Set<Id> leadId = new Set<Id>();

for (CampaignMember cm :{leadId.add(cm.CampaignId);

Integer i = [SELECT count() FROM CampaignMember where CampaignId != '701C0000000ZFdA' and CampaignId=:Leadid and (Star_RatingF__c = '5' OR Star_RatingF__c = '4')];

Campaign newCampaign = new Campaign(id=cm.campaignid, Total_5_4_Star_Leads__c = i );
update newCampaign;}


I was kinda working on that today. I attempted to make an aggregate query map that passes the id of an object as a map key, and the count as the map value. I wasn't able to get it to work however. 


So i decided to create a regular map, and accumulate the total of iterations of that map to get the count.


Pseudo Example:


trigger Contact(before insert)
Map<Id, List<Account>> mapAccounts();

for(Accounts a : [Select Accounts] )
mapAccounts.put(Id, a)

Integer count = 0;

for(Contact c : mapAccounts.get(thisContact.AccountId))



Hope this helps.


This seems to work, thanks for your help!

trigger StarRatingCampaign on CampaignMember (after insert){
Set<Id> CampaignMemberID = new Set<Id>();

Set<Id> CampaignID = new Set<Id>();
for (CampaignMember cm :{CampaignID.add(cm.CampaignId);}

Map<Id, set<ID>> mapCampaignMembers=new Map<id,set<ID>>();

for(CampaignMember cmm : [SELECT id FROM CampaignMember where CampaignId != '701C0000000ZFdA' and CampaignId=:Campaignid and (Star_RatingF__c = '5' OR Star_RatingF__c = '4')] )
mapCampaignMembers.put(cmm.Id, CampaignMemberID);

for (CampaignMember cm :{

Set<id> counts = mapCampaignMembers.get(cm.Id);
Integer i = counts.size();
Campaign newCampaign = new Campaign(id=cm.campaignid, Total_5_4_Star_Leads__c = i );
update newCampaign;



This is a greate Site:


It help me a lot.