Challenge - 5 Problems
FOREACH Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of FOREACH loop with integer array
What will be the output of the following PL/pgSQL block?
DO $$
DECLARE
nums integer[] := ARRAY[1, 2, 3];
total integer := 0;
num integer;
BEGIN
FOREACH num IN ARRAY nums LOOP
total := total + num;
END LOOP;
RAISE NOTICE 'Total: %', total;
END $$;PostgreSQL
DO $$ DECLARE nums integer[] := ARRAY[1, 2, 3]; total integer := 0; num integer; BEGIN FOREACH num IN ARRAY nums LOOP total := total + num; END LOOP; RAISE NOTICE 'Total: %', total; END $$;
Attempts:
2 left
💡 Hint
Think about how FOREACH iterates over each element and adds it to total.
✗ Incorrect
The FOREACH loop iterates over each element in the array nums (1, 2, 3) and adds each to total. So total becomes 1+2+3 = 6.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in FOREACH usage
Which option contains a syntax error in using FOREACH to iterate over a text array in PL/pgSQL?
PostgreSQL
DECLARE fruits text[] := ARRAY['apple', 'banana', 'cherry']; fruit text; BEGIN FOREACH fruit IN fruits LOOP RAISE NOTICE '%', fruit; END LOOP; END;
Attempts:
2 left
💡 Hint
Check the correct syntax for iterating over arrays with FOREACH.
✗ Incorrect
FOREACH requires the keyword ARRAY before the array variable to iterate properly. Option A misses ARRAY, causing a syntax error.
❓ optimization
advanced2:00remaining
Optimizing FOREACH loop for large arrays
You have a large integer array and want to sum its elements efficiently in PL/pgSQL. Which approach is the most efficient?
Attempts:
2 left
💡 Hint
Consider built-in SQL functions for aggregation over arrays.
✗ Incorrect
Using unnest() with SELECT SUM() leverages SQL set operations which are faster than looping in PL/pgSQL.
🔧 Debug
advanced2:00remaining
Debugging FOREACH loop with NULL elements
Given the array
ARRAY[1, NULL, 3], what will be the value of total after this PL/pgSQL block?DECLARE
nums integer[] := ARRAY[1, NULL, 3];
total integer := 0;
num integer;
BEGIN
FOREACH num IN ARRAY nums LOOP
total := total + num;
END LOOP;
RAISE NOTICE 'Total: %', total;
END;Attempts:
2 left
💡 Hint
Think about how NULL values affect arithmetic in SQL.
✗ Incorrect
Adding NULL to any number results in NULL in SQL, so total becomes NULL after adding the NULL element.
🧠 Conceptual
expert2:00remaining
Understanding FOREACH loop variable scope
In PL/pgSQL, what is the scope of the loop variable declared in a FOREACH loop iterating over an array?
Attempts:
2 left
💡 Hint
Consider variable visibility rules in PL/pgSQL blocks.
✗ Incorrect
In PL/pgSQL, the FOREACH loop variable must be declared outside the loop beforehand. It retains its value from the last iteration after the loop ends.