Bird
Raised Fist0
PostgreSQLquery~10 mins

FOREACH for array iteration in PostgreSQL - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to iterate over each element in the array using FOREACH.

PostgreSQL
DECLARE
  my_array integer[] := ARRAY[1, 2, 3];
  element integer;
BEGIN
  FOREACH element [1] ARRAY my_array LOOP
    RAISE NOTICE '%', element;
  END LOOP;
END;
Drag options to blanks, or click blank then click option'
AFROM
BOF
CON
DIN
Attempts:
3 left
💡 Hint
Common Mistakes
Using OF instead of IN causes a syntax error.
Using FROM or ON are not valid keywords here.
2fill in blank
medium

Complete the code to declare an array of text values.

PostgreSQL
DECLARE
  fruits text[] := [1];
BEGIN
  NULL;
END;
Drag options to blanks, or click blank then click option'
AARRAY['apple', 'banana', 'cherry']
B['apple', 'banana', 'cherry']
C('apple', 'banana', 'cherry')
D{'apple', 'banana', 'cherry'}
Attempts:
3 left
💡 Hint
Common Mistakes
Using JSON-style [] notation causes errors.
Using parentheses () is for tuples, not arrays.
3fill in blank
hard

Fix the error in the FOREACH loop to correctly iterate over the array.

PostgreSQL
DECLARE
  nums integer[] := ARRAY[10, 20, 30];
  n integer;
BEGIN
  FOREACH n [1] nums LOOP
    RAISE NOTICE '%', n;
  END LOOP;
END;
Drag options to blanks, or click blank then click option'
AIN ARRAY
BIN
CFROM ARRAY
DON ARRAY
Attempts:
3 left
💡 Hint
Common Mistakes
Using IN without ARRAY causes syntax errors.
Using ON ARRAY or FROM ARRAY are invalid.
4fill in blank
hard

Fill both blanks to create a FOREACH loop that iterates over a text array and prints each fruit.

PostgreSQL
DECLARE
  fruits text[] := ARRAY['apple', 'banana', 'cherry'];
  fruit text;
BEGIN
  FOREACH fruit [1] [2] fruits LOOP
    RAISE NOTICE '%', fruit;
  END LOOP;
END;
Drag options to blanks, or click blank then click option'
AOF
BIN
CARRAY
DTABLE
Attempts:
3 left
💡 Hint
Common Mistakes
Using OF instead of IN causes errors.
Using TABLE instead of ARRAY is invalid here.
5fill in blank
hard

Fill all three blanks to declare an integer array, iterate over it with FOREACH, and print each number.

PostgreSQL
DECLARE
  numbers [1] := [2];
  num integer;
BEGIN
  FOREACH num [3] numbers LOOP
    RAISE NOTICE '%', num;
  END LOOP;
END;
Drag options to blanks, or click blank then click option'
Ainteger[]
BARRAY[5, 10, 15]
CIN ARRAY
Dtext[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using text[] instead of integer[] for numbers.
Not using IN ARRAY in FOREACH loop.
Incorrect array literal syntax.

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