In continuation of my previous article about Oracle Cursors, here I will share the use of cursors for loops with an appropriate example.
The process of opening, fetching, and closing is handled implicitly by a cursors FOR LOOP. If there is a need to FETCH and PROCESS each and every record from a cursor , the cursor FOR LOOP is helpful for that.
Let's learn about the implicit cursor for loop using the following table ORDERS and example:
| Supp_id | Supp_name | Items | Customer_id |
| 111 | AAA | DEO | #128 |
| 222 | BBB | Perfume | #32 |
| 333 | CCC | Perfume | #121 |
| 444 | DDD | DEO | #88 |
| 555 | EEE | DEO | #199 |
| 666 | FFF | Perfume | #02 |
| 777 | GGG | DEO | #105 |
Implicit Cursor for Loop
Note: Here, an implicit cursor FOR LOOP statement prints the name of the supplier and supplier id of the entire item named as DEO whose customer has an ID greater than 100.
Note: Here, an implicit cursor FOR LOOP statement prints the name of the supplier and supplier id of the entire item named as DEO whose customer has an ID greater than 100.
- BEGIN
- //Beginning of FOR LOOP//
- FOR item IN (
- SELECT ,supp_id,supp_name
- FROM Orders
- WHERE Supp_id LIKE '%DEO%'
- AND Customer_id > 120
- ORDER BY supp_name
- )
- LOOP
- DBMS_OUTPUT.PUT_LINE
- ('Supplier Name = ' || item.supp_name || ', Supplier ID = ' || item.Supp_id);
- END LOOP;
- //End of FOR LOOP//
- END;
Result
| Supp_id | Supp_name |
| Supplier ID = 111 | Supplier Name = AAA |
| Supplier ID = 555 | Supplier Name = EEE |
| Supplier ID = 777 | Supplier Name = GGG |
Explicit Cursor for Loop
Note: In the following example, an explicit cursor FOR LOOP statement prints the name of the supplier and supplier id of the entire item named PERFUME whose customer has an ID lesser than 100.

Join the conversation! Your thoughts help the community grow.