6

SOQL ’for’ Loops

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 more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

ServiceNow Stripe