Cursors in MySQL
IMPLEMENTATION OF CURSORS
IN MYSQL
1. AIM
To understand the concept of cursors in MySQL and implement them inside stored procedures with examples.
2. THEORY
✔ What is a Cursor?
A cursor in MySQL is a database object used to retrieve and process query results row-by-row.
Normally, SQL works in a set-oriented way (all rows at once).
But sometimes you need record-by-record processing, such as:
-
Calculating values per row
-
Generating summaries
-
Performing row-by-row validations
-
Creating logs for each row
This is where cursors are useful.
3. CURSOR COMPONENTS
To use a cursor in MySQL, you need:
✔ 1. Declare variables
Used to store individual column values from each row.
✔ 2. Declare a cursor
Specifies the SELECT query whose rows you want to process.
✔ 3. Declare a CONTINUE HANDLER
This handles the situation when the cursor reaches the end.
✔ 4. Open the cursor
✔ 5. Fetch rows inside LOOP
✔ 6. Close the cursor
4. GENERAL STRUCTURE OF A CURSOR
5. LAB EXAMPLES
Example 1: Cursor to Display Employee Names One by One
Create table:
Create procedure using cursor:
Execute:
Example 2: Cursor to Calculate Bonus for Each Employee
Bonus = 10% of salary
Add to log table.
Create log table:
Procedure using cursor:
Execute:
Example 3: Cursor to Update Salary for Each Employee
Increase salary by 5%.
Execute:
⭐ Example 4: Cursor with IF Condition
Show only employees earning more than 50,000.
6. IMPORTANT POINTS ABOUT CURSORS
| Feature | Value |
|---|---|
| Row-by-row processing | ✔ |
| Used only inside stored procedures | ✔ |
| Needs OPEN, FETCH, CLOSE | ✔ |
| Requires NOT FOUND handler | ✔ |
| Slow for large records | ✔ because row-by-row |
7. LAB PRACTICE QUESTIONS
-
Write a cursor to display all student names one by one.
-
Create a cursor to calculate total marks of every student and insert into a result table.
-
Use a cursor to apply a 5% discount to all products.
-
Create a cursor to copy only customers from a specific city into another table.
-
Write a cursor to find employees with salary less than average salary.
8. RESULT
Cursors were successfully created, executed, and tested in MySQL using stored procedures.
Comments
Post a Comment