SOQL For Loop

Biswajeet   March 19, 2014   No Comments on SOQL For Loop

The SOQL for loops iterate over ALL the sObjects returned by a SOQL query. Here is the syntax for the for loop in SOQL:

Option 1 – (Include the SOQL in the loop definition):

for (someVariables : [soql_query])
{
    //Your Code
}

Note: The variables above must be of the same type as the sObject that are returned by the soql_query. Here’s an example below of a simple for loop function that uses the clauses WHERE and LIKE:

String s = ‘Biswajeet Samal’;
For ( Lead a : [SELECT Id, Name from Lead where Name = : (s)])
{
    //Your Code
}

Option 2 – (Create a list of results (sObject list) first and then loop through them):

// Create a list of account records from a SOQL query
Account[] accs = [SELECT Id, Name FROM Account WHERE Name =  'Biswajeet Samal'];
  
// Loop through the list and update the Name field
for(Account a : accs){
   a.Name = 'Biswajeet Samal';
}