0
0
PostgreSQLquery~10 mins

FOREACH for array iteration in PostgreSQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - FOREACH for array iteration
Start FOREACH loop
Pick next element from array
Execute loop body with element
More elements?
YesPick next element
No
End loop
The FOREACH loop picks each element from the array one by one and runs the loop body with that element until all elements are processed.
Execution Sample
PostgreSQL
DO $$
DECLARE
  arr integer[] := ARRAY[10, 20, 30];
  val integer;
BEGIN
  FOREACH val IN ARRAY arr LOOP
    RAISE NOTICE 'Value: %', val;
  END LOOP;
END $$;
This code loops through each number in the array and prints it.
Execution Table
StepCurrent Element (val)ActionOutput
110Start loop, pick first elementValue: 10
220Pick next elementValue: 20
330Pick next elementValue: 30
4N/ANo more elements, exit loopLoop ends
💡 All elements in the array have been processed, so the loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
valNULL10203030
Key Moments - 3 Insights
What is the value of 'val' after the loop ends?
30. It retains the value of the last element assigned during the loop (see variable_tracker 'Final' column).
What happens if the array is empty?
The loop body never runs because there are no elements to pick, so no output is produced.
Can FOREACH be used with arrays of types other than integers?
Yes, FOREACH works with any array type, like text[], boolean[], etc., as long as the loop variable matches the element type.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'val' at step 2?
A10
B20
C30
DNULL
💡 Hint
Check the 'Current Element (val)' column at step 2 in the execution_table.
At which step does the FOREACH loop end?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look for the row where the action says 'No more elements, exit loop' in the execution_table.
If the array was empty, what would the output be?
ANo output
BValue: NULL
CError
DValue: 0
💡 Hint
Refer to the key_moments section about empty arrays and loop execution.
Concept Snapshot
FOREACH loops through each element in an array.
Syntax: FOREACH var IN ARRAY array_var LOOP ... END LOOP;
Each iteration assigns the next element to var.
Loop ends when all elements are processed.
Works with any array type matching var's type.
Full Transcript
The FOREACH loop in PostgreSQL lets you run code for each element in an array. It picks elements one by one, assigns them to a variable, and runs the loop body. When no elements remain, the loop stops. If the array is empty, the loop body never runs. This works for arrays of any type, as long as the loop variable matches the element type. The example code loops through an integer array and prints each number. The variable holding the element changes each step and retains the last value after the loop ends.