How to use loop in apex Salesforce

Loops are a fundamental concept in Apex programming that allow developers to execute a block of code repeatedly until a specific condition is met. In Salesforce Apex, loops are commonly used to process records from SOQL queries, collections like lists and maps, and bulk data operations.

In this article, we will learn how to use loops in Apex, explore different types of loops available, and understand best practices for using them efficiently in Salesforce.

Why Loops Are Important in Apex

Salesforce enforces strict governor limits, especially when dealing with database operations. Loops help developers:

  • Process multiple records efficiently
  • Handle bulk data operations
  • Avoid repetitive code
  • Build scalable and reusable logic

Using loops correctly is critical for writing bulk-safe Apex code.

Types of Loops in Apex

Apex supports the following types of loops:

  1. For Loop
  2. For-Each Loop
  3. While Loop
  4. Do-While Loop

Let’s explore each one with examples and use cases.

1. For Loop in Apex

The for loop is used when you know exactly how many times the loop should execute.

Syntax

for(Integer i = 0; i < 5; i++) {

    System.debug(i);

}

How It Works

  • Initialization runs once (Integer i = 0)
  • Condition is checked before every iteration
  • Increment executes after each loop cycle

Use Case

  • Iterating through a fixed range
  • Looping through list indexes

2. For-Each Loop in Apex

The for-each loop is the most commonly used loop in Salesforce because it works efficiently with collections.

Syntax

List<Account> accList = [SELECT Id, Name FROM Account LIMIT 10];

for(Account acc : accList) {

    System.debug(acc.Name);

}

Why It’s Preferred

  • Cleaner syntax
  • No index handling required
  • Bulk-safe and readable

Best Use Case

  • Iterating through lists returned from SOQL queries
  • Processing records in triggers and classes

SOQL For Loop (Best Practice)

Salesforce recommends using SOQL for loops for large datasets.

Syntax

for(Account acc : [SELECT Id, Name FROM Account]) {

    System.debug(acc.Name);

}

Advantages

  • Automatically handles record batching
  • Prevents heap size issues
  • Ideal for large data volumes

3. While Loop in Apex

A while loop runs as long as the specified condition remains true.

Syntax

Integer count = 0;

while(count < 5) {

    System.debug(count);

    count++;

}

Use Case

  • When the number of iterations is not known beforehand
  • Conditional processing

Caution

Always ensure the condition becomes false; otherwise, it can result in an infinite loop.

4. Do-While Loop in Apex

The do-while loop executes the code block at least once, even if the condition is false.

Syntax

Integer num = 0;

do {

    System.debug(num);

    num++;

} while(num < 5);

Key Difference

  • Condition is checked after executing the loop body

Using Loops with Maps

Maps are frequently used in Apex for key-value data processing.

Example

Map<Id, Account> accMap = new Map<Id, Account>(

    [SELECT Id, Name FROM Account LIMIT 5]

);

for(Id accId : accMap.keySet()) {

    System.debug(accMap.get(accId).Name);

}

Loops in Triggers (Bulk-Safe Example)

Triggers always handle multiple records, so loops are mandatory.

Example

trigger AccountTrigger on Account (before insert) {

    for(Account acc : Trigger.new) {

        acc.Description = ‘Created via Trigger’;

    }

}

This ensures:

  • Bulk processing
  • No governor limit violations

Common Mistakes to Avoid

  • Writing SOQL queries inside loops
  • Performing DML operations inside loops
  • Using unnecessary nested loops
  • Ignoring bulk processing

Best Practices for Using Loops in Apex

  • Always design loops for bulk data
  • Use collections to store records before DML
  • Prefer SOQL for loops for large datasets
  • Avoid nested loops when possible
  • Keep logic inside loops lightweight

Conclusion

Loops are an essential building block in Apex programming. Whether you are working with triggers, classes, batch jobs, or integrations, understanding how to use loops correctly helps you write efficient, scalable, and governor-limit-safe code.

By mastering for loops, for-each loops, while loops, and do-while loops, you can confidently handle complex data processing in Salesforce.

Scroll to Top