A cursor in MySQL is used to process the rows returned by a query one row at a time. Cursors are mainly used inside stored procedures and stored functions when we need to perform an operation on each row individually.
- Processes query results row by row.
- Used inside stored programs such as procedures.
- Allows individual rows to be read and processed.
- Uses DECLARE, OPEN, FETCH and CLOSE statements.
Syntax
DECLARE cursor_name CURSOR FORSELECT column1, column2FROM table_name;
Steps to Use a Cursor
A cursor generally follows these four steps:
- DECLARE : Define the cursor and the query.
- OPEN : Open the cursor.
- FETCH : Retrieve rows one at a time.
- CLOSE : Close the cursor.
Example
Consider the following employees table:
| employee_id | employee_name | salary |
|---|---|---|
| 1 | John | 50000 |
| 2 | Emily | 60000 |