Challenge - 5 Problems
Loop Mastery in PL/pgSQL
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple FOR loop in PL/pgSQL
What will be the output of the following PL/pgSQL block?
DO $$
DECLARE
i INT;
BEGIN
FOR i IN 1..3 LOOP
RAISE NOTICE 'Number: %', i;
END LOOP;
END $$;PostgreSQL
DO $$ DECLARE i INT; BEGIN FOR i IN 1..3 LOOP RAISE NOTICE 'Number: %', i; END LOOP; END $$;
Attempts:
2 left
💡 Hint
The FOR loop runs from 1 to 3 inclusive.
✗ Incorrect
The FOR loop iterates over the range 1 to 3, printing each number with RAISE NOTICE.
❓ query_result
intermediate2:00remaining
WHILE loop behavior with decrement
What will be the output of this PL/pgSQL block?
DO $$
DECLARE
counter INT := 3;
BEGIN
WHILE counter > 0 LOOP
RAISE NOTICE 'Count: %', counter;
counter := counter - 1;
END LOOP;
END $$;PostgreSQL
DO $$ DECLARE counter INT := 3; BEGIN WHILE counter > 0 LOOP RAISE NOTICE 'Count: %', counter; counter := counter - 1; END LOOP; END $$;
Attempts:
2 left
💡 Hint
The loop stops when counter is no longer greater than 0.
✗ Incorrect
The WHILE loop runs while counter is 3, 2, and 1, then stops before 0.
📝 Syntax
advanced2:00remaining
Identify the syntax error in this FOR loop
Which option contains the correct syntax for a FOR loop iterating over integers 1 to 5 in PL/pgSQL?
Attempts:
2 left
💡 Hint
PL/pgSQL uses two dots .. for ranges.
✗ Incorrect
The correct syntax uses 'IN 1..5' to specify the range in a FOR loop.
❓ query_result
advanced2:00remaining
Output of nested loops with conditional exit
What will be the output of this PL/pgSQL block?
DO $$
DECLARE
i INT;
j INT;
BEGIN
FOR i IN 1..2 LOOP
FOR j IN 1..3 LOOP
IF i * j > 3 THEN
EXIT;
END IF;
RAISE NOTICE 'i=% j=%', i, j;
END LOOP;
END LOOP;
END $$;PostgreSQL
DO $$ DECLARE i INT; j INT; BEGIN FOR i IN 1..2 LOOP FOR j IN 1..3 LOOP IF i * j > 3 THEN EXIT; END IF; RAISE NOTICE 'i=% j=%', i, j; END LOOP; END LOOP; END $$;
Attempts:
2 left
💡 Hint
The inner loop exits when i*j > 3, skipping further j values.
✗ Incorrect
For i=1, j=1,2,3 all print since 1*3=3 not >3. For i=2, j=1 prints (2*1=2 not >3), j=2 checks 4>3 and EXITs before printing.
🧠 Conceptual
expert2:00remaining
Effect of EXIT vs CONTINUE in loops
In PL/pgSQL loops, what is the difference between EXIT and CONTINUE statements?
Attempts:
2 left
💡 Hint
Think about how to stop a loop vs skip one iteration.
✗ Incorrect
EXIT ends the loop immediately; CONTINUE skips the rest of the current iteration and moves to the next.