Create a For Loop to Iterate Through a SOQL Query in Salesforce

In Salesforce SOQL, using a for loop within a for loop is a common approach to process and manipulate records efficiently. Using a for loop, we can iterate over the query results and apply logic directly to each record.

In this Salesforce tutorial, I will explain how to create a for loop to iterate through a SOQL query in Apex code and the method to use a for loop to iterate through a list.

SOQL Query with For Loop to Iterate through Records

We will follow the single variable format to write an SOQL query with For Loop. In this example, we will query the Account records, where the value of the Industry field is ‘Technology.’

The single variable format of a for loop directly iterates through the results of a SOQL query without the need to store the results in a list.

Syntax of For loop in SOQL single variable format:

for (SObject variableName : [SOQL Query]) {
    // Code to process each record
}

We have executed a for loop in a public apex class AccountProcessor.

SOQL query with For Loop:

public class AccountProcessor {
    public static void processAccounts() {
        for (Account acc : [SELECT Id, Name, Industry FROM Account WHERE Industry = 'Technology']) {
            if (acc.Industry == 'Technology') {
                acc.Name += ' - Tech';
                System.debug('Processing Account: ' + acc.Name);
            }
        }
    }
}

Calling the above method in the Apex anonymous window using the code below.

AccountProcessor.processAccounts();

Output:

Salesforce SOQL query with for loop

In the above output, we have fetched account records according to the conditions applied to the SQOL query. Then, with the condition of a for loop, the account names were displayed as “Processing Account: account name.”

In this process, the account object is directly used in the loop. SOQL query is executed once, and each record is processed in turn. This approach minimizes memory usage as it does not store the query results in a separate variable.

SOQL Query with For Loop to Iterate through Records in List Variable Format

In Salesforce SOQL, the list variable format involves first storing the results of a SOQL query into a list and then iterating through the list using a for loop.

For example, you want to iterate over all open opportunities, so we will execute the SOQL query inside the for loop in the following way.

Syntax to use the For loop in SOQL in List variable format:

List<SObject> listName = [SOQL Query];
for (SObject variableName : listName) {
    // Code to process each record
}

Anonymous Apex Code:

In this example, I have executed the Apex code in the anonymous window.

List<Opportunity> openOpps = [SELECT Id, Name, StageName, Amount FROM Opportunity WHERE StageName = 'Open'];
for (Opportunity opp : openOpps) {
    System.debug('Opportunity Name: ' + opp.Name);
    System.debug('Stage: ' + opp.StageName);
    System.debug('Amount: ' + opp.Amount);
}

Output:

Insert For loop in SOQL to iterate through list in Salesforce

As we can see, the query results are sorted in the ‘OpenOpps‘ list. This way, we can execute the SOQL Query with a For Loop to iterate through records in a list variable format.

How to get a SOQL query out of a for loop in Salesforce

In the Salesforce Apex code, getting a ‘For Loop‘ out of an SOQL query is necessary to avoid exceeding the governor limit of 100 SOQL queries per transaction. In a code pattern where we execute an SOQL query inside a for loop, it leads to the query being executed multiple times.

The solution is to query all required records at once and store them in a collection, such as a Map or a List.

For example, you have to query Opportunities for a list of Contacts, and then, instead of executing the SOQL query inside the for loop, you can follow the code below.

In the code below, I have also added the system.debug statements as a proof of concept to show that the code is working fine.

APEX anonymous code:

//  Query the contacts
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = : '0015i00000lU1hsAAC'];
System.debug('Queried Contacts: ' + contacts);

// Collect Contact IDs
Set<Id> contactIds = new Set<Id>();
for (Contact c : contacts) {
    contactIds.add(c.Id);
}
System.debug('Collected Contact IDs: ' + contactIds);

// Query Opportunities
List<Opportunity> opportunities = [SELECT Id, Name, ContactId FROM Opportunity WHERE ContactId IN :contactIds];
System.debug('Queried Opportunities: ' + opportunities);

// Map Opportunities by ContactId
Map<Id, List<Opportunity>> contactToOppsMap = new Map<Id, List<Opportunity>>();
for (Opportunity opp : opportunities) {
    if (!contactToOppsMap.containsKey(opp.ContactId)) {
        contactToOppsMap.put(opp.ContactId, new List<Opportunity>());
    }
    contactToOppsMap.get(opp.ContactId).add(opp);
}
System.debug('Contact to Opportunities Map: ' + contactToOppsMap);

// Process Opportunities for Each Contact
for (Contact c : contacts) {
    List<Opportunity> opps = contactToOppsMap.get(c.Id);
    System.debug('Processing Contact: ' + c + ' | Opportunities: ' + opps);
    if (opps != null) {
    }
}

Output:

In the debug console output, we will see the list of mapped opportunity records with the contact records.

How to add for loop outside the SOQL query

In the above code, we have executed only one SOQL query regardless of the number of Contact records. With this method, we can handle large data sets. Also, this method clears the separation of querying and processing logic and avoids hitting the governor’s limits.

Conclusion

In this Salesforce tutorial, we learned about the methods of using the for loop in SOQL queries for single variable and list variable formats. After this, we also discussed how to execute SOQL queries in Apex code outside the for loop to avoid situations like hitting governor limits and running the same query multiple times.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.