Challenge - 5 Problems
WHILE Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple WHILE loop procedure
Consider the following SQL procedure that uses a WHILE loop to insert numbers into a table. What will be the content of the table Numbers after executing the procedure?
SQL
CREATE TABLE Numbers (num INT); CREATE PROCEDURE InsertNumbers() BEGIN DECLARE i INT DEFAULT 1; WHILE i <= 3 DO INSERT INTO Numbers VALUES (i); SET i = i + 1; END WHILE; END; CALL InsertNumbers(); SELECT * FROM Numbers ORDER BY num;
Attempts:
2 left
💡 Hint
Think about how the WHILE loop increments and when it stops.
✗ Incorrect
The loop starts at 1 and inserts values until i is greater than 3. It inserts 1, 2, and 3, then stops.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in this WHILE loop procedure
Which option contains the correct syntax for a WHILE loop inside a SQL procedure?
SQL
CREATE PROCEDURE CountDown() BEGIN DECLARE x INT DEFAULT 5; WHILE x > 0 DO SET x = x - 1; END WHILE; END;
Attempts:
2 left
💡 Hint
Check punctuation carefully after loop blocks.
✗ Incorrect
In SQL procedures, each statement must end with a semicolon. The END WHILE must be followed by a semicolon.
❓ optimization
advanced2:00remaining
Optimizing a WHILE loop to avoid unnecessary iterations
Given a procedure that sums numbers from 1 to N using a WHILE loop, which option optimizes the loop to reduce the number of iterations?
SQL
CREATE PROCEDURE SumNumbers(IN N INT, OUT total INT) BEGIN DECLARE i INT DEFAULT 1; SET total = 0; WHILE i <= N DO SET total = total + i; SET i = i + 1; END WHILE; END;
Attempts:
2 left
💡 Hint
Think about mathematical formulas that can replace loops.
✗ Incorrect
The sum of numbers from 1 to N can be calculated directly with the formula N*(N+1)/2, avoiding the loop.
🔧 Debug
advanced2:00remaining
Debugging an infinite loop in a WHILE procedure
This procedure causes an infinite loop. What is the cause?
SQL
CREATE PROCEDURE InfiniteLoop() BEGIN DECLARE counter INT DEFAULT 1; WHILE counter <= 5 DO -- Missing increment END WHILE; END;
Attempts:
2 left
💡 Hint
Check if the loop variable changes inside the loop.
✗ Incorrect
Without incrementing counter, the condition counter <= 5 is always true, causing an infinite loop.
🧠 Conceptual
expert2:00remaining
Understanding variable scope in WHILE loops inside procedures
In a SQL procedure, what happens to a variable declared inside a WHILE loop block compared to one declared before the loop?
Attempts:
2 left
💡 Hint
Think about how SQL handles variable declarations inside blocks.
✗ Incorrect
Variables declared inside the loop block are re-initialized each iteration, so they do not retain values between iterations.