Difference between list for loop and SOQL for loop in Apex

Apex code to update all accounts with null region field with value ‘CAM’.

Using SOQL List for loop – Create a list of sObject result list first and then loop through the list

List accountList = [Select Id, Name,region__c From Account];
List accUpdateList = new List();

for(Account acc : accountList) {
if(acc.regioon__c == null) {
        Account.region__c = 'CAM';
        accUpdateList.add(acc);
    }
}
if(!accUpdateList.isEmpty())
    update accUpdateList ;

Using SOQL for loop – Use the SOQL query in the for loop

List accUpdateList = new List();
for(Account acc : [Select Id, Name,region__c From Account]) {
    if(acc.regioon__c == null) {
        Account.region__c = 'CAM';
        accUpdateList.add(acc);
    }
}
if(!accUpdateList.isEmpty())
    update accUpdateList

SOQL and SOSL query can retrieve either the count of a query or a number of object records.  SOQL for loop retrieves all sObjects using efficient chunks of call to the query and queryMore methods.

Using both the option developer can check the heap memory, using the 1st option heap size will be considerably more then 2nd option, So to avoid heap size limit error developer should always use a SOQL for loop to process query results that returns many records.

Querying Large Data Sets – 
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s