Lab 07 Loops
Lab 07 Loops
Class: BSCS-13
Objectives
The objective of this Lab is to understand the basics of Looping statements in PL/SQL.
Tools/Software Requirement
SQL Developer
VSCode
or you can directly run your commands in
https://livesql.oracle.com/next/
Description
PL/SQL provides different types of loops to repeatedly execute a block of statements. Loops are
fundamental in automating repetitive tasks, processing data sets, and performing iterative
calculations.
Types of Loops in PL/SQL
1. Basic Loop
2. WHILE Loop
3. FOR Loop
4. Nested Loops
Example
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
EXIT WHEN counter > 5;
END LOOP;
END;
CS236: Advance Database Systems Page 2
While loop
The WHILE loop evaluates a condition before executing the loop’s body. If the condition is
TRUE, the loop executes; if it’s FALSE, the loop terminates.
Example
DECLARE
counter NUMBER := 1;
BEGIN
WHILE counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
END LOOP;
END;
For Loop
The FOR loop is used when the number of iterations is known in advance. It automatically
increments the loop counter.
Example
BEGIN
FOR counter IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
END LOOP;
END;
Nested Loops
Loops can be nested inside one another to perform complex iterations over multi-dimensional
data.
Example
BEGIN
FOR i IN 1..3 LOOP
FOR j IN 1..2 LOOP
DBMS_OUTPUT.PUT_LINE('i = ' || i || ', j = ' || j);
END LOOP;
END LOOP;
END;
Deliverables:
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.