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.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.