Skip to main content

PL/SQL Cursor FOR LOOP πŸ”„

Mentor's Note: The manual 4-step cursor process (Open, Fetch, Exit, Close) is a lot of work. The Cursor FOR LOOP is the modern "Auto-Pilot" version. It handles all four steps for you in a single line of code! πŸ’‘


🌟 The Scenario: The Automatic Scanner πŸ“„β€‹

Imagine you have a stack of 500 documents.

  • Manual: Pick up page -> Scan -> Put down -> Check if more left.
  • Auto-Pilot: You put the whole stack into an Automatic Document Feeder. The machine handles everything until the stack is empty. βœ…

πŸ’» 1. The Basic Syntax​

You don't even need to declare a variable to hold the dataβ€”Oracle creates a Record for you automatically!

DECLARE
CURSOR c_emp IS SELECT first_name, salary FROM employees;
BEGIN
-- πŸš€ Logic: Oracle OPENS, FETCHES, and CLOSES automatically
FOR r_emp IN c_emp LOOP
DBMS_OUTPUT.PUT_LINE(r_emp.first_name || ' earns ' || r_emp.salary);
END LOOP;
END;

πŸ’» 2. Inline Cursors​

You don't even have to declare the cursor! You can write the query directly in the loop.

BEGIN
FOR r_dept IN (SELECT department_name FROM departments) LOOP
DBMS_OUTPUT.PUT_LINE('Dept: ' || r_dept.department_name);
END LOOP;
END;

πŸ›‘οΈ 3. Why use Cursor FOR LOOP? (Architect's Note)​

  1. Safety: You can never "forget" to close the cursor. No more memory leaks! ⚑
  2. Speed: Oracle internally optimizes these loops using Bulk Fetching (fetching rows in groups of 10 or 100), making them faster than manual loops.
  3. Clean Code: Your programs will be 50% shorter and much easier for other developers to read.

πŸ“Š Comparison: Manual vs. Automatic​

TaskManual (Loop)Cursor FOR LOOP
OpenRequiredAutomatic βœ…
FetchRequiredAutomatic βœ…
Exit CheckRequiredAutomatic βœ…
CloseRequiredAutomatic βœ…

πŸ“ˆ Learning Path​

πŸ“ Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
πŸ“ Address
2/66 Faram Street, Rustompura
Surat – 395002, Gujarat, India
πŸ“ž Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition β€” Areas We Serve in Surat

Adajanβ€’Althanβ€’Amroliβ€’Athwaβ€’Athwalinesβ€’Bhagalβ€’Bhatarβ€’Bhestanβ€’Canal Roadβ€’Chowkβ€’Citylightβ€’Dumasβ€’Gaurav Pathβ€’Ghod Dod Roadβ€’Haziraβ€’Jahangirpuraβ€’Kamrejβ€’Kapodraβ€’Katargamβ€’Limbayatβ€’Magdallaβ€’Majura Gateβ€’Mota Varachhaβ€’Nanpuraβ€’New Citylightβ€’Olpadβ€’Palβ€’Pandesaraβ€’Parle Pointβ€’Piplodβ€’Punaβ€’Randerβ€’Ring Roadβ€’Rustampuraβ€’Sachinβ€’Salabatpuraβ€’Sarthanaβ€’Sosyo Circleβ€’Udhnaβ€’Varachhaβ€’Ved Roadβ€’Vesuβ€’VIP Road
πŸ“ž Call SirπŸ’¬ WhatsApp Sir