0
0
PostgreSQLquery~10 mins

FOREACH for array iteration in PostgreSQL - Interactive Code Practice

Choose your learning style9 modes available
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.