Thursday, 11 September 2025

What is Cursor? Why do we need cursor? Example.


 


Q. What is a Cursor?

Ans:

A cursor is a pointer/handle to the result set of a query in PL/SQL.

It lets us process rows one by one (row-by-row iteration).

Think of it like:

👉 SQL gives you a whole table of results.

👉 A cursor lets you pick each row, work with it, then move to the next.


Q. Why Do We Need Cursors?

Ans:

SQL by itself works in sets (all rows at once).

Example:

UPDATE students SET grade='A' WHERE marks > 90.

→ These updates all qualifying rows in one go. 

But PL/SQL is procedural. 

Sometimes you need to:

1. Fetch one row, process it, make a decision

2. Then move to next row, apply a different logic

👉 In such cases, we require cursors.


Example Without Cursor (Problem Case)

Suppose we have a table Students (roll_no, name, marks)

Now we want to give grades like:

Marks ≥ 90 → Grade 'A'

Marks 75–89 → Grade 'B'

Marks < 75 → Grade 'C'

We cannot write one simple SQL UPDATE because logic is conditional per row.


Notes in Detail:









data structures and algorithms Web Developer

No comments:

Post a Comment