Concepts of Cursors: Implicit & Explicit; Declare, open, fetch, close

Cursors act as database pointers that let your programs fetch, inspect, and process multi row query results safely line by line.

10 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The single row limitation

Imagine your manager at TicketDesk asks you to display the details of every single ticket currently marked as Open. You confidently write a standard SQL SELECT statement inside a PL/SQL block. But the moment your query returns more than one row, the Oracle database engine instantly throws a nasty TOO_MANY_ROWS exception and crashes your program. Standard PL/SQL variables can only hold one value or row at a time. How can you safely fetch and process multiple rows sequentially without crashing your database system?

Theory

The Warehouse Conveyor Belt

Think of your database table like a large warehouse storage room filled with thousands of product boxes. If you try to carry all the boxes in your arms at the exact same time, you will drop them and cause a total disaster. Instead, you setup a narrow conveyor belt. The warehouse supervisor places one box onto the belt at a time. You stand at the end, pick up the single box, process it, and wait for the next one to arrive. A cursor is that conveyor belt for your data rows.

Theory

Defining Cursors in Oracle PL/SQL

In the Oracle database dialect, a cursor is a private memory area allocated by the system to execute SQL statements and store the returned active row set. Cursors act as pointers that let you fetch and process a multi row query result line by line. Oracle uses two categories of cursors: implicit cursors, which are automatically created by the system for every single DML statement, and explicit cursors, which are fully declared and managed by the programmer for multi row queries.

At a glance

Structural differences between implicit and explicit cursors in Oracle databases

FeatureImplicit CursorExplicit Cursor
CreationAutomatically created by Oracle for all single SQL queriesManually defined by the programmer in the DECLARE section
Row CapacityDesigned for single row operations or whole bulk setsSpecifically built to fetch and process multiple rows line by line
Lifecycle ControlManaged entirely by the system from start to finishControlled manually using explicit DECLARE, OPEN, FETCH, and CLOSE commands
Default NamesReferred to using the generic keyword SQLIdentified by a custom name assigned by the programmer

Practical

Walking Through an Open Tickets Query Lifecycle

-- Enable text printing in Oracle SQL*Plus
SET SERVEROUTPUT ON;

DECLARE
  -- Step 1: Declare the explicit cursor with its query
  CURSOR c_open_tickets IS
    SELECT id, title FROM tickets
    WHERE status = 'Open';
    
  v_id tickets.id%TYPE;
  v_title tickets.title%TYPE;
BEGIN
  -- Step 2: Open the cursor to allocate memory and run query
  OPEN c_open_tickets;
  
  LOOP
    -- Step 3: Fetch the current row data into local variables
    FETCH c_open_tickets INTO v_id, v_title;
    
    -- Exit loop when no more rows are found
    EXIT WHEN c_open_tickets%NOTFOUND;
    
    DBMS_OUTPUT.PUT_LINE('Processing Ticket ID: ' || v_id || ' - ' || v_title);
  END LOOP;
  
  -- Step 4: Close the cursor to release database server resources
  CLOSE c_open_tickets;
END;
/

Copy and open Oracle FreeSQL
Oracle FreeSQL is a free online editor for Oracle SQL. The code is copied first: paste it there and run it.

Quiz

Which explicit cursor lifecycle command is responsible for executing the associated SELECT query and allocating active memory space?

  1. DECLARE
  2. OPEN
  3. FETCH
  4. CLOSE
Show the answer

OPEN

While DECLARE creates the structural blueprint in code, the OPEN statement actually executes the underlying SQL query inside the database engine and populates the active area with rows. FETCH merely retrieves the current row, and CLOSE releases the memory space.

Think first

Mental Challenge: The Order of Variables

Suppose your cursor selects id first then title from the tickets table. What happens if you write FETCH c_open_tickets INTO v_title, v_id where variables are accidentally swapped? Think about the consequence mentally before tapping to reveal.

Show the answer

Oracle maps values strictly by sequential position, not by variable names. If v_title is a VARCHAR2 and id is a NUMBER, Oracle will attempt a conversion. If it cannot convert an alphanumeric title into a numeric ID variable, your block will instantly fail with a runtime VALUE_ERROR exception. Always match variables precisely with the cursor SELECT column sequence.

Watch out

The Floating Cursor Memory Leak

The most frequent mistake Indian BCA students make in university lab exams is forgetting the explicit CLOSE command. Unlike implicit cursors, an explicit cursor stays completely open inside database server memory even after your PL/SQL block completes execution. If this block runs repeatedly within an application loop, it continuously leaks active context areas until the database runs entirely out of cursor slots and throws the dreaded maximum open cursors exceeded crash.

Theory

Enterprise Record Navigation and Mobile Frameworks

In major enterprise customer support platforms like helpdesk ticket routers, explicit cursors handle heavy batch migrations and daily SLA status sweeps safely across millions of rows without overloading server RAM. You will reuse this exact pointer extraction concept next semester in your Sem 3 SQLite mobile database course, where you will use structural Android loop cursor adapters to paint database records onto a smartphone screen list view.

Summary

Key takeaways

  • A cursor is a private database memory zone used to handle query results line by line safely.
  • Implicit cursors are automatically managed by Oracle for standard single row queries and updates.
  • Explicit cursors require a strict manual four step cycle: DECLARE, OPEN, FETCH, and CLOSE.
  • The FETCH statement copies values from the active dataset into local variables sequentially.
  • Always close explicit cursors to prevent high server memory leaks and context slot exhaustion.
  • Memory hook: Declare the loop, open the line, fetch the row, and close on time!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Cursors and Exception Handling, Packages, Triggers

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Concepts of Cursors: Implicit & Explicit; Declare, open, fetch, close · Mastering SQL - PL/SQL (SEC-02 option A) · Gri-Learn