Which One Is Better: Loop with SOQL or Create a List Then Loop?

Question
Which Approach Is Better for Performance: Using a SOQL For Loop or Querying into a List and Then Looping?
In some triggers, I’ve seen the following code pattern:
for (Account a : [SELECT Id FROM Account WHERE Id IN :mapAccount.keySet()]) {
// Code
}In other cases, the code is written like this:
List<Account> listAccount = [SELECT Id FROM Account WHERE Id IN :mapAccount.keySet()];
for (Account a : listAccount) {
// Code
}From a performance perspective, are these two approaches the same? Which one is preferred for better efficiency?
Start your Salesforce career with our Salesforce training in Chandigarh, offering hands-on experience and job-ready skills through real-world projects. Sign up now for a free demo session!
Answer
When working with Salesforce triggers or Apex classes, you may encounter two common patterns for iterating over query results. These patterns involve either looping directly with a SOQL query or first storing the query results in a list and then iterating through the list. Here’s an example of each approach:
Using a SOQL For Loop:
for (Account a : [SELECT Id, Name FROM Account WHERE Id IN :mapAccount.keySet()]) {
// Perform operations on each account
}Using a List with a For Loop:
List<Account> accountList = [SELECT Id, Name FROM Account WHERE Id IN :mapAccount.keySet()];
for (Account a : accountList) {
// Perform operations on each account
}Both approaches have their pros and cons, and their suitability depends on the context in which you are using them. Here’s a detailed explanation of when to prefer each:
SOQL For Loop
The SOQL For Loop is optimal when memory usage is a concern. This approach processes one record at a time and uses lazy loading to retrieve records in smaller chunks. It is particularly helpful when working with large datasets, as it avoids consuming excessive heap memory.
For example, if you need to process a very large number of attachments but want to avoid memory limits, you can use a SOQL For Loop:
for (Attachment att : [SELECT Body FROM Attachment WHERE ParentId = :parentId]) {
att.Body = encrypt(att.Body);
update att;
}In this case, the SOQL For Loop ensures that only the necessary rows are loaded into memory as they are needed, which can prevent heap size errors.
List with For Loop
The List with For Loop is preferable when CPU efficiency and simplicity are priorities. Retrieving the results into a list before iterating can sometimes execute faster because it eliminates the overhead of lazy loading during the iteration. Additionally, if you need to use the query results multiple times, having them in a list is more efficient.
For example, to update 10,000 accounts, you could first retrieve all accounts into a list and process them in bulk:
List<Account> updates = [SELECT Name FROM Account LIMIT 10000];
for (Account acc : updates) {
acc.Name = acc.Name.toUpperCase();
}
update updates;This approach is simple and effective when memory constraints are not a significant concern.
Performance Considerations
The performance differences between these approaches usually come down to memory versus CPU usage:
- Use the SOQL For Loop when:
- You need to process very large datasets.
- Memory consumption is a concern.
- The query results are used only within the loop.
- Use the List with For Loop when:
- You need to reference the query results multiple times outside the loop.
- CPU time is a higher priority than memory efficiency.
- The dataset size is manageable within heap size limits.
Edge Cases and Best Practices
In some cases, the SOQL For Loop may offer unique advantages. For instance, it allows early termination of the loop, which can reduce the number of rows counted against the governor limits. Here’s an example:
for (Account acc : [SELECT Name FROM Account ORDER BY Name ASC]) {
if (acc.Name == 'SpecificName') {
break;
}
}This approach can save on SOQL row limits if you break out of the loop early.
Conversely, for simpler use cases where memory limits are not a concern, the List with For Loop may result in cleaner, more maintainable code.
Conclusion
The choice between the SOQL For Loop and the List with For Loop depends on the specific requirements of your implementation. If memory is a concern or you are dealing with large datasets, the SOQL For Loop is the better choice. If CPU time and simplicity are more important, or if you need to use the query results multiple times, go with the List with For Loop. Both approaches are valid tools, and understanding when to use each will help you write efficient and scalable Apex code.
Salesforce Training in Chandigarh – Accelerate Your Career Today!
Designed for a deep, immersive learning experience, our Salesforce training equips you with the skills to succeed in the CRM industry. Covering Salesforce Admin, Developer, and AI domains, the program combines theoretical knowledge with practical, real-world applications. Through industry-relevant projects and assignments, you’ll tackle complex business challenges with Salesforce solutions. Guided by expert instructors, you’ll enhance your technical skills and deepen your understanding of the CRM ecosystem.
Our Salesforce training in Chandigarh offers personalized mentorship, expert interview coaching, and comprehensive certification exam preparation to help you excel in the competitive job market. With hands-on project experience, detailed study materials, and continuous guidance, you’ll build confidence and expertise to secure top certifications and demonstrate practical skills that employers value. Start your Salesforce journey today and unlock exciting career opportunities!
Take the first step toward a thriving Salesforce career—sign up for a FREE demo session today..!

