SOQL For Loop


Unlike in SQL, 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])





Note that 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 = ‘The Salesforce General’;

For ( Lead a : [SELECT Id, Name from Lead  where Name = : (s)])





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
List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'SalesforceGeneral']; 
// Loop through the list and update the Name field
for(Account a : accs){
   a.Name = 'The Salesforce General';