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
St2018St2018 

How to optimize code receiving too many soql queries: 101

lI am receiving too many soql queries: 101.
Need elp on how I  can redo this bit of code to reduce the number of queries to stop the receiving the error.
private Id hasTemplateBuilding(Apttus__APTS_Agreement__c agreement) {
        if(agreement != null) {
            List<Template_Assignment__c> building = [SELECT Template__c FROM Template_Assignment__c WHERE Building__c =: agreement.Building__c];
            if(building.size() == 1) {
                return building[0].Template__c;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
Kt YadavKt Yadav
Hi Stephanie 2008,

You have to bulkified your code to handle multiple aggrements so that it will not give 101.Below is the code snippet that you can try.

private Map<Id,Id> hasTemplateBuilding(List<Apttus__APTS_Agreement__c> agreementList) {
        
        
        Map<Id,Id> BuildTemplateMap = new Map<id,Id>();// map of  building & Template
            if(agreementList != null && !agreementList.isEmpty()) {
                for(Apttus__APTS_Agreement__c agr : agreementList){
                    BuildTemplateMap.put(agr.Building__c,null);
                }
            
            
                for(Template_Assignment__c template : [SELECT Template__c FROM Template_Assignment__c WHERE Building__c in : BuildTemplateMap.keySet()]){
                    if(BuildTemplateMap.containsKey(template.Building__c)){
                        BuildTemplateMap.put(template.Building__c,template.Template__c);
                    }
                }
            }
            if(BuildTemplateMap.size()!= 0 && !BuildTemplateMap.isEmpty())
                return BuildTemplateMap;
            else
                return null;
    }

Now at the place of calling you can get the Template id by comparing map values.
I hope it will resolve your issue.
Happy Coding  :)
Raj VakatiRaj Vakati
try this
 
private Map<Id,Id> hasTemplateBuilding(List<Apttus__APTS_Agreement__c> agreementList) {
	
	
	Set<Id> builderSet = new Set<id>();
		if(agreementList != null && !agreementList.isEmpty()) {
			for(Apttus__APTS_Agreement__c agr : agreementList){
				builderSet.add(agr.Building__c);
			}
		
				Map<Id,Id> BuildTemplateMap = new Map<id,Id>();// map of  building & Template

			for(Template_Assignment__c template : [SELECT Template__c FROM Template_Assignment__c WHERE Building__c in : builderSet]){
				if(BuildTemplateMap.containsKey(template.Building__c)){
					BuildTemplateMap.put(template.Building__c,template.Template__c);
				}
			}
		}
		if(BuildTemplateMap.size()!= 0 && !BuildTemplateMap.isEmpty())
			return BuildTemplateMap;
		else
			return null;
}