SOQL ’for’ Loops
Chapter Topics
- SOQL Basics (Salesforce Object Query Language)
- How to Write SOQL in APEX
- SOQL Variable Binding in APEX
- SOQL Keywords
- SOQL Date Literals In Salesforce
- SOQL Aggregate Query
- 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 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.