+ Start a Discussion
priya bhawna shettypriya bhawna shetty 

soql related

hi friends

can anyone tell me...

what is the error we get when we use soql quiry in any for loop?

thnks

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
Using a query inside a for loop will result in "too many soql queries" for large transactions. To avoid this, use maps and be sure to aggregate results into a single query.

All Answers

digamber.prasaddigamber.prasad

Hi,

 

There could be different types of error. Let me know your specific question if any.

 

Happy to help you!

Mariappan PerumalMariappan Perumal

It won't show any error. But when you try process records in bulk format (Inserting/Updating more than 200 records in a single transacation ) it can't process that in single go .

 

So We need to pull all the records in the single query outside of Loop Statement and Process the List of records for DML Operation.

 

Kindly let me know incase you need more question on this.

digamber.prasaddigamber.prasad

Hi,

 

You need to query list of records inside for loop and your problem will be solved. Look at below code snippet I have queried list of account records and updated that, so you don't need to run DML outside for loop query.

 

for(List<Account> lstAccount : [Select Id, Name from Account]){
	for(integer i=0; i<lstAccount.size(); i++){
		lstAccount[i].Name = 'Test Account' + i;
	}
	update lstAccount;
}

 

Let me know if you have any specific question around this.

 

Happy to help you!

 

 

sfdcfoxsfdcfox
Using a query inside a for loop will result in "too many soql queries" for large transactions. To avoid this, use maps and be sure to aggregate results into a single query.
This was selected as the best answer