MySQL + SQL · Lesson 100
Cursors in MySQL
What is a Cursor?
A cursor lets you process query results ONE ROW AT A TIME inside a stored procedure. Normal SQL works on whole sets; a cursor is for row-by-row logic.
Cursor Structure
DECLARE done INT DEFAULT 0;
DECLARE v_name VARCHAR(50);
DECLARE cur CURSOR FOR SELECT name FROM students;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
read_loop: LOOP
FETCH cur INTO v_name;
IF done = 1 THEN LEAVE read_loop; END IF;
-- process v_name here
END LOOP;
CLOSE cur;
When to Use
Cursors are slow compared to set-based SQL. Use them only when you truly must handle each row separately.
Summary
- A cursor processes rows one by one inside a procedure.
- Steps: DECLARE, OPEN, FETCH in a loop, CLOSE. Use sparingly.