fbpx

Free Salesforce Developers Tutorials >

Chapter 6 - SOQL >

SOQL ’for’ Loops

SOQL ’for’ Loops

What You’ll Learn


tickWhat is SOQL 'for' Loop in Apex?

tickHow 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 Status Number of Records
Open 24
Close 13
On Hold 7
salesforce-developer

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *