
Loops in Salesforce Apex

Table of Contents:
- What is a Loop?
- do {statement} while (Boolean_condition)
- while (Boolean_condition)
- for (initialization; Boolean_exit_condition; increment);
- for (variable : array_or_set) statement;
- for (variable : [inline_soql_query]) statement;
- Interview Questions on Loops in Salesforce
- Learn Salesforce in Pune
What is a Loop?
A loop is a block of code that is repeated until a specified condition is met. Salesforce apex supports both traditional and advanced loop types. Using a loop statement, we can execute a statement or group of statements multiple times.
Read more: Classes – Salesforce Apex
Below is the flow diagram of a loop followed by most programming languages.
CRS Info Solutions offers a comprehensive and dynamic Salesforce online course career building program for beginners, covering admin, developer, and LWC concepts.
do {statement} while (Boolean_condition)
The do-while
loop is a control flow statement in programming that executes a block of code at least once and then repeatedly as long as a specified condition is true. It differs from a traditional while
loop in that it guarantees at least one execution of the code block, regardless of the condition, because the condition is evaluated after the code block has executed. This makes it particularly useful in scenarios where the code needs to run at least once before checking a condition, such as processing user input or iterating over a collection with an unknown number of elements.
Read more: Objects – Salesforce Apex
The loop consists of the do
keyword followed by the code block, and then the while
keyword with the condition in parentheses. If the condition is true after the first execution, the loop continues; otherwise, it exits, and the program continues with the next statement after the loop.
Syntax:
do {
code_block
}
while (condition);
Counting Down: This loop starts with a count
value of 5 and decrements it in each iteration. The loop continues as long as count
is greater than 0. It’s useful for counting down from a specific number.
Collection is one of the important concept, checkout: Collections in Salesforce Apex
Integer count = 5;
do {
System.debug('Count: ' + count);
count--;
} while (count > 0);
Summing Numbers:
This loop calculates the sum of the first five positive integers. It starts with number
set to 1 and adds it to sum
in each iteration, incrementing number
by 1 each time. The loop runs until number
is greater than 5.
Integer sum = 0;
Integer number = 1;
do {
sum += number;
number++;
} while (number <= 5);
System.debug('Sum: ' + sum);
Using a Boolean Condition:
This loop uses a Boolean variable continueLoop
to control its execution. It starts with count
set to 1 and increments it in each iteration. When count
reaches 3, it sets continueLoop
to false, causing the loop to exit. This pattern is useful when the loop’s continuation depends on a condition that might change within the loop’s body.
Read more: Array methods in Salesforce Apex
Boolean continueLoop = true;
Integer count = 1;
do {
System.debug('Count: ' + count);
if (count == 3) {
continueLoop = false;
}
count++;
}
while (continueLoop);
Processing a List:
This loop iterates through a list of strings (fruits) and prints each element. It uses an index
variable to track the current position in the list and increments it in each iteration. The loop continues as long as index
is less than the size of the list, ensuring that each element is processed.
Read more: String methods in Salesforce apex
List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};
Integer index = 0;
do {
System.debug('Fruit: ' + fruits[index]);
index++;
}
while (index < fruits.size());
while (Boolean_condition) statement;
A while loop in Apex executes a block of code repeatedly until a particular Boolean condition is satisfied. A while
loop is used to repeatedly execute a block of code as long as a specified condition evaluates to true
. Here’s an improved and more detailed version of the code block, along with an explanation:
Syntax:
// Initialize a counter variable
int counter = 0;
// Use a while loop to execute the code block as long as the counter is less than 5
while (counter < 5) {
// Inside the loop, print the value of the counter
System.out.println("Counter: " + counter);
// Increment the counter to avoid an infinite loop
counter++;
}
In this example:
- The condition
counter < 5
is checked before each iteration of the loop. As long as this condition istrue
, the loop continues to execute. - The code block inside the loop prints the current value of
counter
and then increments it by 1 usingcounter++
. - The loop will execute a total of 5 times, printing the values of the counter from 0 to 4. Once
counter
reaches 5, the conditioncounter < 5
evaluates tofalse
, and the loop terminates.
Checkout: DML statements in Salesforce
for (initialization; Boolean_exit_condition; increment) statement;
Apex provides three variants of for loop:
The Standard for loop:
In Salesforce Apex, a for
loop is a control flow statement that allows you to execute a block of code repeatedly, with a specified number of iterations or until a certain condition is met. There are two main types of for
loops in Apex: the traditional for
loop and the for-each
loop.
Here’s a sample code snippet of a traditional for
loop in Apex:
Syntax:
// Define a list of integers
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
// Use a traditional for loop to iterate over the list and double each number
for (Integer i = 0; i < numbers.size(); i++) {
// Access and modify each element in the list
numbers[i] = numbers[i] * 2;
System.debug('Doubled Number: ' + numbers[i]);
}
Read more: Salesforce apex programming examples
In this example:
- The loop starts with an initialization expression (
Integer i = 0
), which sets the starting index for iteration. - The condition (
i < numbers.size()
) is checked before each iteration. The loop continues as long as this condition evaluates totrue
. - After each iteration, the increment expression (
i++
) is executed to update the loop counter. - Inside the loop, the code accesses each element of the
numbers
list using the loop counteri
and doubles its value. The updated value is then printed to the debug log.
The list or set iteration for loop:
Syntax:
// Define a list of strings representing fruit names
List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};
// Use a for-each loop to iterate over the list of fruits
for (String fruit : fruits) {
// Inside the loop, you can access and perform operations on each fruit
System.debug('Fruit: ' + fruit);
// Additional code to perform operations on each fruit
}
Checkout: Data types in Salesforce Apex
In this example:
String
is the data type of the elements in the list. You can replace this with any other data type or sObject type as needed.fruit
is the loop variable that represents each individual element in the list.fruits
is the list being iterated over. You can also use a set instead of a list.- Inside the loop, you can access the current element using the loop variable (
fruit
) and perform any necessary operations.
The for-each
loop is a convenient and readable way to iterate over collections in Apex. It abstracts away the need for using indices to access elements, making the code cleaner and less error-prone, especially when working with complex data structures.
The SOQL for loop:
Syntax:
// Define a SOQL query to retrieve a list of Account records
String soqlQuery = 'SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000';
// Use a SOQL for loop to iterate over the query results
for (Account acc : Database.query(soqlQuery)) {
// Inside the loop, you can access and manipulate each Account record
System.debug('Account Name: ' + acc.Name);
// Additional code to perform operations on each record
}
Checkout: Variables in Salesforce Apex
In this example:
Account
is the sObject type we’re querying. You can replace this with any other sObject type as needed.acc
is the loop variable that represents each individual record returned by the SOQL query.Database.query(soqlQuery)
is used to execute the SOQL query string dynamically. You can also use a static query directly in the loop, likefor (Account acc : [SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000])
.- Inside the loop, you can access the fields of each
Account
record using dot notation (e.g.,acc.Name
) and perform any necessary operations.
Using a SOQL for loop is efficient because it processes the records in batches, reducing the number of queries and the amount of heap space used, which is particularly important in Apex due to governor limits.
for (variable : array_or_set) statement;
In a list or set loop, the elements in a list or set are iterated over. The for (variable : array_or_set)
statement in Apex, also known as the for-each loop, is a powerful and concise way to iterate over elements in a collection, such as an array, list, or set. This looping construct simplifies the process of accessing and manipulating each element in the collection, making the code more readable and easier to maintain. By eliminating the need for explicit indexing, the for-each loop reduces the chances of errors and enhances code clarity, making it a preferred choice for developers when working with collections in Salesforce’s Apex programming language.
Read more: SOQL in Salesforce
Syntax:
// Define a list of integers
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
// Use a for-each loop to iterate over the list
for (Integer num : numbers) {
// Inside the loop, you can access and manipulate each element
System.debug('Number: ' + num);
// Additional code to perform operations on each element
}
In this example:
Integer
is the data type of the elements in the list. You can replace this with any other data type or sObject type as needed.num
is the loop variable that represents each individual element in the list.numbers
is the list being iterated over. You can also use a set instead of a list.- Inside the loop, you can access the current element using the loop variable (e.g.,
num
) and perform any necessary operations.
for (variable : [inline_soql_query]) statement;
The SOQL for loop iterates over all the sObject records that the SOQL query returns. The Salesforce Object Query Language (SOQL) for loop is a powerful feature in Apex, Salesforce’s proprietary programming language, that allows developers to iterate over a set of records retrieved by a SOQL query. This construct is particularly useful for efficiently processing large volumes of data while adhering to Salesforce’s governor limits. By leveraging SOQL for loops, developers can easily access, manipulate, and perform operations on each record in the result set, making it an essential tool in the development of custom Salesforce applications and functionalities.
Syntax:
// Define a SOQL query to retrieve a list of Account records
String soqlQuery = 'SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000';
// Use a SOQL for loop to iterate over the query results
for (Account acc : Database.query(soqlQuery)) {
// Inside the loop, you can access and manipulate each Account record
System.debug('Account Name: ' + acc.Name);
// Additional code to perform operations on each record
}
In this example:
Account
is the sObject type we’re querying. You can replace this with any other sObject type as needed.acc
is the loop variable that represents each individual record returned by the SOQL query.Database.query(soqlQuery)
is used to execute the SOQL query string dynamically. You can also use a static query directly in the loop, likefor (Account acc : [SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000])
.- Inside the loop, you can access the fields of each
Account
record using dot notation (e.g.,acc.Name
) and perform any necessary operations.
Master Salesforce in Pune: Unlock New Career Opportunities with Top Skills
In 2024, Salesforce has become an essential skill for professionals, especially in tech-savvy cities like Pune. As one of India’s fast-growing IT hubs, Pune is home to numerous companies that depend on Salesforce for managing customer relationships (CRM) and streamlining business operations. Developing expertise in Salesforce, including roles like Admin, Developer (Apex), Lightning, and Integration, can give your career a significant boost in Pune and help you stay ahead in 2025. With high demand for these skills, you can expect competitive salaries in this field.
Why Salesforce is a Critical Skill to Develop in Pune
Pune is a major player in India’s IT landscape, with a strong presence of multinational companies and a steady need for professionals with specialized skills. Salesforce is at the center of this demand due to its prominence as a CRM platform. Pursuing Salesforce training in Pune positions you to take advantage of the city’s thriving tech industry. Companies like Deloitte, Accenture, Infosys, TCS, and Capgemini are actively seeking certified Salesforce professionals to manage and enhance their CRM systems.
Being a certified Salesforce expert can open doors to a wide range of job opportunities. Pune offers competitive salaries for Salesforce developers and administrators, making this a highly attractive skill to learn. Certification from a recognized training provider can set you apart and accelerate your career growth in this booming industry.
Why Choose CRS Info Solutions for Salesforce Training in Pune?
CRS Info Solutions is renowned for offering top-tier Salesforce training in Pune. Our courses cover key modules, including Salesforce Admin, Developer, Integration, Marketing Cloud, CPQ, and Lightning Web Components (LWC). The curriculum is designed to give you both theoretical knowledge and practical experience, ensuring you’re well-prepared for real-world scenarios. At CRS Info Solutions, we focus on equipping you with the skills necessary to excel and succeed in leading organizations in Pune. Kickstart your Salesforce journey with us today and become an expert ready to take on new challenges.
Sign up now for a free demo at CRS Info Solutions Salesforce Course Pune!
Interview Questions on Loops in Salesforce
1. Explain the different types of for
loops available in Salesforce Apex and when you would use each type.
Salesforce Apex supports three types of for
loops:
- Traditional
for
loop for-each
loopSOQL
for
loop
Example 1: Traditional for
loop
This loop is used when you know the exact number of iterations.
for(Integer i = 0; i < 5; i++) {
System.debug('Iteration: ' + i);
}
Example 2: for-each
loop
This loop is used for iterating over collections, like lists or sets.
List<String> names = new List<String>{'John', 'Jane', 'Doe'};
for(String name : names) {
System.debug('Name: ' + name);
}
Example 3: SOQL for
loop
Used for handling large record sets efficiently by processing in chunks.
for(Account acc : [SELECT Id, Name FROM Account]) {
System.debug('Account Name: ' + acc.Name);
}
2. What is the main difference between a for-each
loop and a traditional for
loop in Apex, and when should you use each?
The traditional for
loop is index-based, and you can control the loop iteration using an index variable, while the for-each
loop is used to iterate directly over collections like lists, sets, and maps. Use a traditional for
loop when you need more control over the iteration process (e.g., skipping elements, reversing), and use a for-each
loop when you want to simply traverse all elements of a collection.
Example: Traditional for
loop
List<String> names = new List<String>{'John', 'Jane', 'Doe'};
for (Integer i = 0; i < names.size(); i++) {
System.debug('Index ' + i + ': ' + names[i]);
}
Example: for-each
loop
for (String name : names) {
System.debug('Name: ' + name);
}
3. Describe how a while
loop works in Salesforce Apex and provide an example scenario where it would be appropriate to use one.
A while
loop repeatedly executes a block of code as long as the specified condition is true
. It is commonly used when the number of iterations is not known in advance.
Example:
apexCopy codeInteger count = 0;
while (count < 5) {
System.debug('Count: ' + count);
count++;
}
In this example, the loop will continue running as long as count
is less than 5.
4. How can you optimize a for
loop in Salesforce Apex to avoid hitting governor limits when working with large data sets?
To avoid hitting governor limits in Salesforce Apex, you can optimize loops by using the SOQL for
loop, which processes records in batches, or by implementing bulkification to process records in smaller chunks.
Example: SOQL for
loop for large data sets
for (Account acc : [SELECT Id, Name FROM Account]) {
// Process each account record individually
System.debug('Account Name: ' + acc.Name);
}
This ensures that Salesforce retrieves and processes data in manageable chunks rather than retrieving all records at once.
5. What is a do-while
loop in Salesforce Apex, and how is it different from a standard while
loop? Give an example.
A do-while
loop is similar to a while
loop, but it guarantees that the loop executes at least once, as the condition is evaluated after the loop body is executed. In contrast, a while
loop evaluates the condition before executing the loop body.
Example:
Integer count = 5;
do {
System.debug('Count: ' + count);
count--;
} while (count > 0);
In this example, the loop will execute at least once, even if the initial condition (count > 0
) is false.