Loops in Salesforce Apex (Complete Guide with Real-Time Examples)

In Salesforce Apex, loops are among the most important concepts every developer must understand.

Loops help you execute a block of code multiple times based on a condition. This is very useful when working with multiple records in Salesforce, such as Accounts, Contacts, or Opportunities.

In real-time projects, developers often need to process large amounts of data. Instead of writing the same code again and again, loops allow us to automate repetitive tasks.

For example, if you want to update 1000 contact records, you can use a loop to process each record one by one efficiently. This makes your code cleaner, faster, and easier to maintain.

In Salesforce Apex, loops are very useful when you need to go through multiple records and apply some conditions. For example, a company wants to identify high-priority customers.

As a Salesforce developer, I write an Apex loop to go through all Account records. Within the loop, an if statement checks whether the customer’s total purchase amount exceeds $10,000.

In this article, I will explain how to use loops in Salesforce Apex. In this, we will understand how to declare and use them to implement complex business logic and automate processes.

What are Loops in Salesforce Apex?

In Salesforce Apex, loops are similar to those in other programming languages, which are used to execute a block of code repeatedly based on a specific condition.

They help automate repetitive tasks, such as processing a collection of records or performing calculations.

A loop is a programming structure that repeats a set of instructions until a specific condition is met. In Salesforce Apex, loops are commonly used to process collections like Lists, Sets, and Maps.

Loops help in:

  • Processing multiple records
  • Automating repetitive tasks
  • Implementing business logic
  • Performing calculations

Without loops, handling large data in Salesforce would be very difficult.

Types of Loops in Salesforce Apex

  • for Loop in Salesforce Apex
  • for each Loop in Salesforce Apex
  • while Loop in Salesforce Apex
  • do-while Loop in Salesforce Apex

1. for Loop in Salesforce Apex

In Salesforce Apex, a for loop is used to repeat a block of code a specific number of times or to iterate over a range of values.

Once the loop executes the specified number of times, it stops executing. It consists of three main parts: initializationcondition, and increment.

Syntax: Declare a for Loop in Salesforce Apex

for ( initialization; condition; increment ) {  
   // logic;
}

For example, we want to display the numbers from 1 to 20 that are divisible by 3. We can use a for loop.

In the Apex code below, I create a for loop. Then, initialized to 0, we want to display the numbers from 1 to 20; for that, we added the condition i <= 20. To increase the number, we use the i++ operator.

Then, to find the number divisible by 3, we need to use the math class and the mod function, since the % operator is not supported in Salesforce Apex.

As you execute the Apex for loop below, you will obtain the numbers that are divisible by 3.

for ( Integer i = 0; i <= 20; i++ ) {
        if ( math.mod(i, 3) == 0 ) {
                System.debug(' ' +i);  
            }
}
Salesforce Apex for Loop

2. for-each Loop in Salesforce Apex

In Salesforce Apex, a for-each loop is primarily used with SObjects to iterate over collections such as lists, sets, or maps.

Syntax: Declare for each Loop in Salesforce Apex

for ( DataType variableName : collection ) {
    // logic;
}

For example, we want to fetch account records with warm account ratings and display them using Salesforce Apex.

In the Apex code below, I declare a list of accounts that store account records we retrieved using a SOQL query with a rating of ‘warm’, and set a limit of 7 records.

After that, in the for each loop, the list of records is assigned to acc, which is an instance of the account object. Using that instance, we display the records that we want.

List<Account> accList = [ SELECT Id, Name, Rating FROM Account WHERE Rating = 'warm' LIMIT 7 ];
        for ( Account acc : accList ) {
            System.debug( ' Account Name : '+acc.Name + ' Rating : '+acc.Rating );
        }     

First, I will show what happens if you don’t use each loop to display the records.

Salesforce Apex Result Without for each loop

Then, as you execute the for each loop, the output will be as shown in the image below.

Loops in Salesforce Apex

3. while Loop in Salesforce Apex

while loop in Salesforce Apex is a control flow statement that executes code repeatedly as long as a given condition remains true.

The condition is checked before each iteration, and the loop continues until the condition becomes false.

Syntax: Declare a while Loop in Salesforce Apex

while (condition) {
    // logic;
}

For example, we want to display the even numbers between a particular range and their sum. Within a while loop, we enter the condition, then execute the logic we want.

        Integer startno = 2, sum=0;
        while (startno <= 20) {
            System.debug(+startno);
            startno = startno + 2;
            sum = sum + startno;
          }
    System.debug( 'Sum of first 20 Even no is :' +sum );      
    }
Salesforce Apex While Loop

4. do-while Loop in Salesforce Apex

A do-while loop in Salesforce Apex is similar to a while loop, but the difference is that the code block inside the loop is executed at least once before the condition is checked.

The condition is evaluated after each iteration, ensuring the loop executes at least once, even if the condition is initially false.

Syntax: Declare a do-while Loop in Salesforce Apex

do {
    // logic;
} while (condition);

For example, we want to process a batch of records and stop when no more records are needed. Here, we defined the batchSize variable’s specified size (batchSize = 10).

It is useful when you need to perform operations on many records without loading them all at once.

The offset starts at 0 and is used to “skip” records during each query. It is incremented by batchSize (10) after each iteration. Then, the List is declared to store the contact records.

Then, in the do block, we used a loop to iterate over the list, using an instance of the contact object to display each record.

After processing each batch of contacts, the offset is incremented by batchSize, allowing the next query to skip the already-processed contacts.

Finally, the while condition we provided means the loop continues until conList is empty, indicating that no more contacts remain to be processed.

List<Contact> contacts;
        Integer offset = 0;
        Integer batchSize = 10;
        List<Contact> conList = new List<Contact>();
        
        do {
            conList = [ SELECT Id, Name FROM Contact LIMIT :batchSize OFFSET :offset ];
            for ( Contact c : conList ) {
                System.debug( ' Contact Name :  ' + c.Name );
            }
            offset = offset + batchSize;
        } while ( !conList.isEmpty() );
Salesforce Apex Do While Loop

As you execute the above Apex code, you can see the output, which displays the contact names available in the contact list.

Difference Between while and do-while

Featurewhile Loopdo-while Loop
Condition checkBefore executionAfter execution
Runs at least onceNoYes

Conclusion

I hope you have got an idea about how loops work in Salesforce Apex. Loops help us run the same logic many times without writing extra code. By using if conditions within loops, you can control which records or data are processed.

Loops in Salesforce Apex are essential for handling repetitive tasks and processing large datasets efficiently. Understanding how to use different types of loops, along with best practices, helps you write optimized and scalable code.

If you follow proper techniques like bulkification and avoid common mistakes, you can easily work with large volumes of data in Salesforce without hitting governor limits.

You may like to read:

live webinar

Salesforce Data Cloud with Agentforce Data Library

In this live webinar, we will showcase how Salesforce AI Agents use business data and documents to provide intelligent responses using Agentforce Data Library and Salesforce Data Cloud.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

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