Apex - SOQL For Loop

This type of for loop is used when we do not want to create the List and directly iterate over the returned set of records of the SOQL query. We will study more about the SOQL query in subsequent chapters. For now, just remember that it returns the list of records and field as given in the query.


for (variable : [soql_query]) { code_block }


for (variable_list : [soql_query]) { code_block }

One thing to note here is that the variable_list or variable should always be of the same type as the records returned by the Query. In our example, it is of the same type as APEX_Invoice_c.

Flow Diagram

Apex For Loop


Consider the following for loop example using SOQL for loop.

// The same previous example using For SOQL Loop
List<apex_invoice__c> PaidInvoiceNumberList = new
List<apex_invoice__c>();   // initializing the custom object records list to store
                           // the Invoice Records
List<string> InvoiceNumberList = new List<string>();

// List to store the Invoice Number of Paid invoices
for (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM
   APEX_Invoice__c WHERE CreatedDate = today]) {
   // this loop will iterate and will process the each record returned by the Query
   if (objInvoice.APEX_Status__c == 'Paid') {
      // Condition to check the current record in context values
      System.debug('Value of Current Record on which Loop is iterating is '+objInvoice);
      //current record on which loop is iterating
      // if Status value is paid then it will the invoice number into List of String

System.debug('Value of InvoiceNumberList with Invoice Name:'+InvoiceNumberList);
Kickstart Your Career

Get certified by completing the course

Get Started