Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

For Loops

Apex supports three variations of the for loop:
  • The traditional for loop:
    1for (init_stmt; exit_condition; increment_stmt) {
    2    code_block
    3}
  • The list or set iteration for loop:
    1for (variable : list_or_set) {
    2    code_block
    3}
    where variable must be of the same primitive or sObject type as list_or_set.
  • The SOQL for loop:
    1for (variable : [soql_query]) {
    2    code_block
    3}
    or
    1for (variable_list : [soql_query]) {
    2    code_block
    3}
    Both variable and variable_list must be of the same sObject type as is returned by the soql_query.

Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Note

Each is discussed further in the sections that follow.