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: Using loops correctly is critical for writing bulk-safe Apex code. Types of Loops in Apex Apex supports the following types of loops: 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 Use Case 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 Best Use Case 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 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 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 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: Common Mistakes to Avoid Best Practices for Using Loops in Apex 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.
How to use loop in apex Salesforce Read More »





