Wednesday 29 August 2012

SOQL For Loops - Apex

Queries can be embedded in the special for syntax. This syntax can be used to loop through the sObjects returned by the query, one at a time, or in batches of 200 sObjects when using a list variable to hold the query results. Using a list variable to hold the query results in the SOQL for loop is a good way to query a large number of records since this helps avoid the heap limit, which is one of the governor execution limits. 
Here is a SOQL for loop example. In this example, each iteration of the for loop operates on a single sObject returned by the query. This is inefficient if you perform database operations inside the for loop because they execute once for each sObject and you’re more likely to reach certain governor limits.
for (Merchandise__c tmp : [SELECT Id FROM Merchandise__c]) {
   // Perform some actions on the single merchandise record. 
    
}
A more efficient way is to use a list variable to hold the batch of records returned by each iteration of the for loop. This allows for bulk processing of database operations. The following example uses a list variable in the for loop.
for (Merchandise__c[] tmp : [SELECT Id FROM Merchandise__c]) {
   // Perform some actions on the single merchandise record. 
    
}

3 comments:

  1. nice tutorials..thanks for sharing such a wonderful information..keep update with your blogs salesforce Online Training Bangalore

    ReplyDelete
  2. I have read your blog its very attractive and impressive. I like your blog. salesforce Online course Hyderabad

    ReplyDelete