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
Vishal_ThoriyaVishal_Thoriya 

How to avoid soql inside for loop ?

Hi everyone ,

 

I am having dout related to governor limit of salesforce ...

 

following is my trigger code

 

i am invoking this trigger for 'Before insert' and 'Before update'

 

How can i avoid my soql queries inside for loop  for this kind of situation....

 

 

if(personalTimeMap.size() > 0){
    	personalList = new List<Personal__c>();
    	for(List<Personal__c> personal : personalMap.values()){
    		personalTime.addAll(personal);
    	}
    	for(Personal__c personalTime : personalList){
    		if([SELECT count() FROM Personal__c WHERE Date_Applied__c = :personalTime.Date_Applied__c AND Assigned_to__c = :personalTime.Assigned_to__c AND Type__c = :personalTime.Type__c AND Type__c = 'Credit'] != 0){
    			personalTime.Date_Applied__c.addError('A personal time with the same applied date, assigned to and type values already exists.');
    		}
    	}
    	
      }

 my code is breaking the governor limit , but can any one help me to come out from this situation?

 

Any kind of help will be very greatly appriciated...

 

Thanks in advance...

 

Vishal.

Best Answer chosen by Admin (Salesforce Developers) 
Chamil MadusankaChamil Madusanka

Please refer following link,

 

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

All Answers

Starz26Starz26

Yo need to create a map to the values in the select statement before all the loops.

 

A bit more of your code so an understanding of your object / fields can be obtained and it will be much eaiser to help....

 

Chamil MadusankaChamil Madusanka

Please refer following link,

 

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

This was selected as the best answer