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?
Topics
- SOQL Basics (Salesforce Object Query Language)
- How to Write SOQL in APEX
- SOQL Variable Binding in APEX
- SOQL Keywords
- Date Literals in SOQL
- SOQL Aggregate Functions
- Child to Parent Relationship
- Parent to Child – Relationship Queries in SOQL
- SOQL Multi level Relationships
- SOQL Return Type
- Salesforce Dynamic SOQL
- 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 Status | Number of Records |
Open | 24 |
Close | 13 |
On Hold | 7 |
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.