liveBook · Manning

Loop

As explained in Learn SQL in a Month of Lunches

A SQL procedural loop repeatedly executes a block of statements while its control conditions permit.

A SQL procedural loop repeats a block of statements while work remains. With a MySQL cursor, the loop fetches one row at a time, performs calculations or updates, and stops when a handler signals that no rows remain. section 22.2.2

Summing qualifying order quantities

A stored procedure opens an AllOrders cursor, enters the named GetOrders loop, and fetches each OrderID. For every order, a query adds quantities sold at the title's list price to _TotalQuantitySold. When the NOT FOUND handler sets _Done to TRUE, IF _Done = TRUE triggers LEAVE GetOrders; the procedure then closes the cursor.

DELIMITER //
 
CREATE PROCEDURE GetTitleTotalQuantitySoldListPrice(
    OUT _TotalQuantitySold int
    )
BEGIN
 
DECLARE _Done boolean DEFAULT FALSE;
 
DECLARE _OrderID int;
 
DECLARE AllOrders CURSOR FOR
 
SELECT OrderID
FROM orderheader;
 
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _Done = TRUE;
 
SET _TotalQuantitySold = 0;
 
OPEN AllOrders;
 
GetOrders: LOOP
 
    FETCH AllOrders INTO _OrderID;
 
    SET _TotalQuantitySold = _TotalQuantitySold +
 
        (SELECT COALESCE(SUM(Quantity),0)
        FROM title t
        INNER JOIN orderitem oi
             ON t.TitleID = oi.TitleID
             AND t.Price = oi.ItemPrice
        WHERE oi.OrderID = _OrderID
        );
 
        IF _Done = TRUE THEN
 
            LEAVE GetOrders;
        END IF;
 
    END LOOP GetOrders;
 
    CLOSE AllOrders;
 
END //
 
DELIMITER ;

Inspect the complete procedure from delimiter setup through cursor declaration, fetch processing, termination, cleanup, and the procedure call. section 22.2.2

Loop requirements differ among relational database products. MySQL requires LOOP for these cursors and uses LEAVE to exit them, so check the target system before reusing the syntax. section 22.2.2

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains declaration, opening, fetching, condition handling, exit, and cleanup, but does not compare complete loop alternatives.
Examples
Demonstrates order totals and annual author payments using named cursor loops.
What it assumes
Assumes basic SQL and stored-procedure familiarity while explaining cursor variables, handlers, fetching, and loop termination.
What you can do after
Operate/configure MySQL cursor loops that fetch rows, calculate values, conditionally insert records, and terminate safely.
How it connects
Connects loops with cursors, stored procedures, FETCH, handlers, IF statements, and LEAVE.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.