Bird
Raised Fist0
PostgreSQLquery~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of the FOREACH statement in PostgreSQL when working with arrays?
easy
A. To convert an array into a string.
B. To loop through each element of an array easily inside PL/pgSQL.
C. To sort the elements of an array in ascending order.
D. To create a new array from existing tables.

Solution

  1. Step 1: Understand FOREACH usage context

    FOREACH is used inside PL/pgSQL to iterate over array elements one by one.
  2. Step 2: Identify the main purpose

    It simplifies looping through arrays without manual index handling.
  3. Final Answer:

    To loop through each element of an array easily inside PL/pgSQL. -> Option B
  4. Quick Check:

    FOREACH loops over array elements [OK]
Hint: FOREACH loops over array elements inside PL/pgSQL [OK]
Common Mistakes:
  • Confusing FOREACH with array creation or sorting
  • Thinking FOREACH works outside PL/pgSQL
  • Assuming FOREACH converts arrays to strings
2. Which of the following is the correct syntax to iterate over an integer array arr using FOREACH in PL/pgSQL?
easy
A. FOREACH element IN ARRAY arr LOOP ... END LOOP;
B. FOREACH element FROM arr LOOP ... END LOOP;
C. FOREACH element ON arr LOOP ... END LOOP;
D. FOREACH element OVER arr LOOP ... END LOOP;

Solution

  1. Step 1: Recall FOREACH syntax

    The correct syntax uses 'IN ARRAY' to specify the array to loop over.
  2. Step 2: Match syntax options

    Only FOREACH element IN ARRAY arr LOOP ... END LOOP; uses 'IN ARRAY' correctly; others use invalid keywords.
  3. Final Answer:

    FOREACH element IN ARRAY arr LOOP ... END LOOP; -> Option A
  4. Quick Check:

    FOREACH ... IN ARRAY ... is correct syntax [OK]
Hint: Use 'IN ARRAY' to loop over arrays with FOREACH [OK]
Common Mistakes:
  • Using FROM, ON, or OVER instead of IN ARRAY
  • Omitting LOOP or END LOOP keywords
  • Trying to use FOREACH outside PL/pgSQL
3. Consider the following PL/pgSQL block:
DECLARE
  arr integer[] := ARRAY[2, 4, 6];
  sum integer := 0;
BEGIN
  FOREACH val IN ARRAY arr LOOP
    sum := sum + val;
  END LOOP;
  RAISE NOTICE '%', sum;
END;

What will be the output when this block runs?
medium
A. Syntax error
B. 24
C. 12
D. 0

Solution

  1. Step 1: Understand the loop iteration

    The FOREACH loops over arr elements: 2, 4, and 6.
  2. Step 2: Calculate the sum

    sum starts at 0, then adds 2 + 4 + 6 = 12.
  3. Final Answer:

    12 -> Option C
  4. Quick Check:

    2 + 4 + 6 = 12 [OK]
Hint: Sum array elements by adding each in FOREACH loop [OK]
Common Mistakes:
  • Assuming FOREACH does not add elements
  • Confusing sum initialization
  • Expecting syntax error due to RAISE NOTICE
4. Identify the error in this PL/pgSQL snippet:
DECLARE
  arr text[] := ARRAY['a', 'b', 'c'];
  ch text;
BEGIN
  FOREACH ch IN arr LOOP
    RAISE NOTICE '%', ch;
  END LOOP;
END;
medium
A. Variable 'ch' must be declared as integer, not text.
B. Array declaration syntax is incorrect.
C. RAISE NOTICE cannot print variables inside loops.
D. FOREACH must use 'IN ARRAY' before the array variable.

Solution

  1. Step 1: Check FOREACH syntax

    FOREACH requires 'IN ARRAY' before the array variable to iterate properly.
  2. Step 2: Identify the error

    The code uses 'IN arr' instead of 'IN ARRAY arr', causing syntax error.
  3. Final Answer:

    FOREACH must use 'IN ARRAY' before the array variable. -> Option D
  4. Quick Check:

    FOREACH ... IN ARRAY ... is correct syntax [OK]
Hint: Always write 'FOREACH var IN ARRAY arr' [OK]
Common Mistakes:
  • Omitting 'ARRAY' keyword in FOREACH
  • Wrong variable type for array elements
  • Misunderstanding RAISE NOTICE usage
5. You want to write a PL/pgSQL function that takes an integer array and returns the count of even numbers using FOREACH. Which of the following code snippets correctly implements this?
hard
A. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val IN ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;
B. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val FROM arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;
C. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOR val IN ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;
D. CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val ON ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql;

Solution

  1. Step 1: Check FOREACH syntax correctness

    CREATE FUNCTION count_evens(arr integer[]) RETURNS integer AS $$ DECLARE val integer; count integer := 0; BEGIN FOREACH val IN ARRAY arr LOOP IF val % 2 = 0 THEN count := count + 1; END IF; END LOOP; RETURN count; END; $$ LANGUAGE plpgsql; uses 'FOREACH val IN ARRAY arr LOOP', which is the correct syntax.
  2. Step 2: Verify logic for counting even numbers

    Inside the loop, it checks if val is even and increments count correctly.
  3. Final Answer:

    FOREACH val IN ARRAY arr LOOP with IF val % 2 = 0 logic -> Option A
  4. Quick Check:

    FOREACH ... IN ARRAY ... and correct IF condition [OK]
Hint: Use 'FOREACH val IN ARRAY arr' and check val % 2 = 0 [OK]
Common Mistakes:
  • Using 'FROM' or 'ON ARRAY' instead of 'IN ARRAY'
  • Confusing FOREACH with FOR loops
  • Missing RETURN statement or wrong logic