Experience Salesforce

SOQL ’for’ Loops

What You’ll Learn

  • What is SOQL 'for' Loop in Apex?
  • How to iterate a loop on SOQL in Apex?

What Is SOQL ’for’ Loops?

SOQL ‘for’ Loops are SOQL statements that can be used inline along with FOR Loops. This means that instead of iterating over a list of records, it is done directly over a SOQL query written inline inside the ‘for’ Loop iteration brackets.

How To Iterate A Loop On SOQL In Apex?

FOR(Position__c pos: [SELECT Name, Max_Salary__c
            FROM Position__c
            WHERE Status__c = 'Open'
        ]) { //code block }

Formats Of SOQL Query

There are two formats for this type of SOQL query:

1. Single Variable Format

Single Variable Format executes the loop once per list of sObject records. The syntax of this format is given here:

 List < Position__c > positionRecordsList = [SELECT Name, Max_Salary__c
                FROM Position__c
                WHERE Status__c = 'Open'
            ];
            for (Position__c pos: positionRecordsList) {
                // code block
            }

2. List Variable Format

List Variable Format executes the loop code once per 200 sObject records.

a:

for(Position__c pos: [SELECT Name, Max_Salary__c
                FROM Position__c
                WHERE Status__c = 'Open'
            ]) {
                //code block
            }

b:

for(List < Position__c > positionList: [SELECT Name, Max_Salary__c
                FROM Position__c
            ]) {
                for (Position pos: positionList) {
                    //code block
                }
            }
Position StatusNumber of Records
Open24
Close13
On Hold7
salesforce-developer
Next Chapter

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale