Challenge - 5 Problems
Cursor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of cursor iteration with FETCH
Consider the following MySQL stored procedure snippet that uses a cursor to iterate over a table
Assuming the
employees with columns id and salary. What will be the value of total_salary after the cursor loop completes?DECLARE done INT DEFAULT FALSE;
DECLARE emp_salary INT;
DECLARE total_salary INT DEFAULT 0;
DECLARE emp_cursor CURSOR FOR SELECT salary FROM employees WHERE id <= 3;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN emp_cursor;
read_loop: LOOP
FETCH emp_cursor INTO emp_salary;
IF done THEN
LEAVE read_loop;
END IF;
SET total_salary = total_salary + emp_salary;
END LOOP;
CLOSE emp_cursor;Assuming the
employees table has rows with id 1, 2, 3 and salaries 1000, 1500, 2000 respectively.Attempts:
2 left
💡 Hint
Think about how the cursor fetches each salary and adds it to the total.
✗ Incorrect
The cursor fetches salaries 1000, 1500, and 2000 one by one and adds them to total_salary. So total_salary becomes 1000 + 1500 + 2000 = 4500.
📝 Syntax
intermediate1:30remaining
Identify the syntax error in cursor declaration
Which of the following cursor declarations in MySQL is syntactically correct?
Attempts:
2 left
💡 Hint
Look at the order of keywords in the declaration.
✗ Incorrect
The correct syntax is 'DECLARE cursor_name CURSOR FOR select_statement;'. Option D follows this syntax exactly.
🔧 Debug
advanced2:00remaining
Why does this cursor loop never end?
Given the following MySQL cursor loop, why does it never exit?
DECLARE done INT DEFAULT FALSE;
DECLARE emp_name VARCHAR(50);
DECLARE emp_cursor CURSOR FOR SELECT name FROM employees;
-- Missing CONTINUE HANDLER
OPEN emp_cursor;
read_loop: LOOP
FETCH emp_cursor INTO emp_name;
IF done THEN
LEAVE read_loop;
END IF;
-- process emp_name
END LOOP;
CLOSE emp_cursor;Attempts:
2 left
💡 Hint
Think about how the loop knows when to stop fetching rows.
✗ Incorrect
Without the CONTINUE HANDLER for NOT FOUND, the 'done' variable never becomes TRUE, so the loop never leaves.
❓ optimization
advanced2:00remaining
Optimizing cursor usage for large datasets
You have a cursor iterating over a large table to calculate the sum of a numeric column. Which approach is more efficient in MySQL?
Attempts:
2 left
💡 Hint
Think about what SQL is best at doing.
✗ Incorrect
SQL aggregate functions like SUM() are optimized and faster than row-by-row cursor processing.
🧠 Conceptual
expert2:30remaining
Understanding cursor scope and variable lifetime
In MySQL stored procedures, what happens to a cursor and its associated variables after the procedure ends?
Attempts:
2 left
💡 Hint
Consider the scope of variables and cursors inside stored procedures.
✗ Incorrect
Cursors and variables declared inside a stored procedure exist only during its execution and are cleaned up afterward.