Class 50 of 58 • Enterprise Database Architecture

SQL Cursors: Complete Lifecycle, Row-by-Row Processing & Performance Pitfalls

Relational databases are engineered from the ground up on the mathematical foundation of Relational Algebra, which operates on sets of tuples simultaneously. In pure SQL, when you execute an UPDATE or SELECT statement, the database engine processes thousands or millions of records as a single unified batch. However, there are scenarios in procedural stored procedures where developers need to inspect, validate, or transform records individually one row at a time. This procedural row-by-row traversal is accomplished using a SQL Cursor.

SQL Cursor Execution Lifecycle: DECLARE, OPEN, FETCH, CLOSE, and DEALLOCATE State Machine

Figure 8.1: Complete state machine and memory lifecycle of a SQL Cursor from initialization to memory deallocation.


1. The Five Stages of the SQL Cursor Lifecycle

Every explicit cursor follows a strict, sequential five-stage state transition lifecycle. Failing to follow these steps leads to severe memory leaks or unreleased database table locks:

• 1. DECLARE: Allocates cursor metadata in memory and associates the cursor pointer with a specific SELECT query. The query is not executed yet.

• 2. OPEN: Executes the associated SELECT statement, populates the working dataset in memory (such as tempdb or PGA buffer), and positions the cursor pointer immediately before the first row.

• 3. FETCH: Reads the column values of the current row into declared local variables and advances the internal row pointer to the next record. The engine updates status flags like @@FETCH_STATUS or triggers an EMPTY / NOT FOUND handler when the end of the dataset is reached.

• 4. CLOSE: Disables the cursor, releases temporary locks held on the result set, and frees the active dataset memory. However, the cursor declaration remains defined, allowing it to be re-opened if needed.

• 5. DEALLOCATE: Completely destroys the cursor definition, releases all allocated kernel data structures, and removes the cursor identifier from the database session.


2. Complete SQL Cursor Implementation (MySQL & T-SQL Examples)

Let us examine a practical business scenario: calculating graduated bonus payments for sales employees and logging each transaction sequentially into an audit table.

-- ===================================================================
-- MySQL Stored Procedure Cursor Implementation
-- ===================================================================
DELIMITER $$

CREATE PROCEDURE ProcessEmployeeBonuses()
BEGIN
    -- 1. Declare local variables to hold fetched row data
    DECLARE done INT DEFAULT FALSE;
    DECLARE v_emp_id INT;
    DECLARE v_salary DECIMAL(10, 2);
    DECLARE v_bonus DECIMAL(10, 2);

    -- 2. Stage 1: DECLARE the cursor
    DECLARE cur_employee CURSOR FOR 
        SELECT emp_id, salary 
        FROM employees 
        WHERE department = 'Sales' AND status = 'Active';

    -- 3. Declare NOT FOUND handler to gracefully terminate iteration
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    -- 4. Stage 2: OPEN the cursor
    OPEN cur_employee;

    -- 5. Stage 3: FETCH loop
    read_loop: LOOP
        FETCH cur_employee INTO v_emp_id, v_salary;
        
        -- Exit loop when no more rows are available
        IF done THEN
            LEAVE read_loop;
        END IF;

        -- Apply procedural business logic
        IF v_salary >= 80000 THEN
            SET v_bonus = v_salary * 0.15;
        ELSE
            SET v_bonus = v_salary * 0.10;
        END IF;

        -- Update employee bonus record
        UPDATE employees 
        SET bonus_amount = v_bonus 
        WHERE emp_id = v_emp_id;

        -- Insert audit log
        INSERT INTO bonus_audit_log (emp_id, bonus_awarded, awarded_at)
        VALUES (v_emp_id, v_bonus, NOW());
    END LOOP;

    -- 6. Stage 4: CLOSE the cursor
    CLOSE cur_employee;
END$$

DELIMITER ;

3. Dry-Run Execution Trace of Cursor Iteration

To understand how the cursor state machine executes row-by-row, consider a table of 3 sales representatives:

Iteration Step Cursor Pointer Position Fetched Variables Evaluated Bonus Status Flag / Handler
OPEN Before Row 1 (BOF) Unassigned N/A done = FALSE
Iteration 1 Row 1 (Emp #101, Salary: $85,000) v_emp_id = 101, v_salary = 85000 $12,750 (15%) done = FALSE
Iteration 2 Row 2 (Emp #102, Salary: $65,000) v_emp_id = 102, v_salary = 65000 $6,500 (10%) done = FALSE
Iteration 3 Row 3 (Emp #103, Salary: $92,000) v_emp_id = 103, v_salary = 92000 $13,800 (15%) done = FALSE
Iteration 4 (EOF) End of Result Set (EOF) No row retrieved N/A Trigger NOT FOUND: done = TRUE → LEAVE LOOP
CLOSE Deallocated from active memory Variables discarded N/A Cursor handles closed

4. Why Cursors are an Anti-Pattern (And How to Eliminate Them)

The Performance Cost of RBAR (Row-By-Agonizing-Row)

Cursors force the database engine to operate against its primary design philosophy. Instead of processing millions of rows using multi-core parallel SIMD instructions in high-speed RAM buffers, a cursor switches CPU context on every row. For a table of 100,000 rows, a cursor performs 100,000 individual query executions, causing severe lock escalation, transactional log bloat, and taking minutes instead of milliseconds.

Rewriting the Cursor using Declarative Set-Based SQL:

Notice how the entire 45-line procedural cursor routine above can be replaced with a single, highly optimized declarative SQL statement that executes in less than 5 milliseconds:

-- High-Performance Set-Based Replacement (Zero Cursors, 100x Faster)
UPDATE employees
SET bonus_amount = CASE 
    WHEN salary >= 80000 THEN salary * 0.15
    ELSE salary * 0.10
END
WHERE department = 'Sales' AND status = 'Active';

-- Batch insert audit log in a single transaction
INSERT INTO bonus_audit_log (emp_id, bonus_awarded, awarded_at)
SELECT emp_id, 
       CASE WHEN salary >= 80000 THEN salary * 0.15 ELSE salary * 0.10 END, 
       NOW()
FROM employees
WHERE department = 'Sales' AND status = 'Active';

Hands-on Student Practice Session (Lab Challenge)

University & Production Lab Assignment

Scenario: You are tasked with migrating an enterprise banking system. A legacy procedure uses a cursor to iterate through customer accounts to detect low-balance accounts (balance < $500) and assess a $25 monthly maintenance fee.

Task 1: Write an explicit SQL cursor procedure that iterates through accounts with balance < 500, deducts the $25 fee, and logs the deduction in fee_ledger.

Task 2: Benchmark the cursor against a set-based UPDATE ... CASE statement and verify why the set-based approach requires zero row-level cursor locks.


Frequently Asked Questions (FAQ)

A SQL Cursor is a database control structure that enables row-by-row traversal (iteration) through a result set. While standard SQL operates on entire sets of records simultaneously, cursors process one individual record at a time. Cursors are primarily used when legacy systems or complex iterative operations (like calling external procedures per record) cannot be expressed cleanly in set-based SQL.

The five phases are: 1) DECLARE (defines cursor name and query), 2) OPEN (executes the query and allocates temporary memory), 3) FETCH (retrieves the next row into local variables), 4) CLOSE (releases active row locks and result sets), and 5) DEALLOCATE / FREE (completely destroys cursor metadata and frees memory).

Cursors cause RBAR (Row-By-Agonizing-Row) processing. Instead of allowing the Cost-Based Optimizer to vectorize data in RAM with parallel threads and SIMD CPU instructions, a cursor forces repetitive context switches, increases lock contention, and runs 10x to 100x slower than set-based UPDATE, CASE, or Window Functions.

Over 95% of procedural cursors can be replaced using modern declarative SQL techniques: 1) Window Functions (ROW_NUMBER, SUM() OVER), 2) Searched CASE expressions for conditional calculations, 3) CTEs for multi-stage transformations, and 4) Set-based UPDATE statements with JOINs.

Next Step in Your SQL Database Learning Path:

Proceed to the next class in sequence to build production mastery of relational database architecture.

Continue to Class 51: Database Security & RBAC → Previous: ← Query Optimization | Full Syllabus


Related SQL Masterclass Lessons & Recommended Next Topics

Stored Procedures & Logic →

Embedding explicit cursors inside procedural database routines.

Replacing Cursors with Sets →

Rewriting iterative cursor loops with fast declarative SQL.

Window Functions vs Cursors →

Using running calculations without row-by-row iteration.

Database Security & Roles →

Securing procedural database scripts and permissions.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!