Loop in PLSQL Explanation
Loop in PLSQL Explanation
• As a quick overview, PL/SQL is the procedural extension for sql, and being
a block language it combines SQL with the procedural features such as
control statements, loops, functions, etc.
• Now, What are loops? Just as the name suggests a loop statement
provides a way of repeating a particular part of any program or any code
block as many times as required.
• This image on the right describes the general working of a loop statement
in most of the programming languages.
• Explaining the ow diagram in the image: As we can see here if compiler
encounters a condition, it checks if the condition is true, it execute the
conditional code, if the condition fails, it exits the control statement,
• This is almost same as the working of the control statements, but. There
may be situations when we need to execute a block of code several times
or need to nd the occurrence of a particular result, we use loop in such
scenarios.
===============================================
• PL/SQL provides the following types of loops for handling the looping
requirements.
• Basic loop
• FOR loop
• While loop
• Nested loop
================================================
Now lets explore each loop in detail.
First is the Basic loop
• BASIC LOOP: Basic loop or simple loop is preferred in PL/SQL code when
there is no surety about how many times the block of code is to be
repeated.
• When we use the basic loop the code block will be executed at least once.
• While using it, following two things must be considered:
• Simple loop always begins with the keyword LOOP and ends with a
keyword END LOOP.
• A basic/simple loop can be terminated at any given point by using the exit
statement or by specifying certain condition by using the statement exit
when.
• Image1: This PL/SQL code initializes a variable `x` with a value of 10 and
enters a loop. Within the loop, it prints the current value of `x` using
`dbms_output.put_line` and increments `x` by 10. It checks if `x` exceeds 50,
and if so, exits the loop. After exiting the loop, it prints the nal value of `x`
concatenated with a message. In essence, it prints multiples of 10 until
reaching or exceeding 50, then displays the nal value of `x`.
When the above code is executed at the SQL prompt, it produces the
following result −
fi
fl
fi
fi
10
20
30
40
50
After Exit x is: 60
• Image2: This PL/SQL code initialises a variable `x` with a value of 10 and
enters a loop. Within the loop, it prints the current value of `x` using
`dbms_output.put_line` and increments `x` by 10. It exits the loop when `x`
exceeds 50 using the `EXIT WHEN` statement. After exiting the loop, it
prints the nal value of `x` concatenated with a message. Essentially, it
prints multiples of 10 until reaching or exceeding 50, then displays the nal
value of `x`. Using `EXIT WHEN` streamlines the code by combining the exit
condition with the loop structure.
When the above code is executed at the SQL prompt, it produces the
following result −
10
20
30
40
50
After Exit x is: 60
1. DECLARE
2. x NUMBER := 0;
3. BEGIN
4. LOOP -- After CONTINUE statement, control resumes here
5. DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' ||
TO_CHAR(x));
6. x := x + 1;
7. IF x < 3 THEN
8. CONTINUE;
9. END IF;
10. DBMS_OUTPUT.PUT_LINE
11. ('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
12. EXIT WHEN x = 5;
13. END LOOP;
14.
15. DBMS_OUTPUT.PUT_LINE (' After loop: x = ' ||
TO_CHAR(x));
16. END;
17. /
After the execution of above code, you will get the following result:
Inside loop: x = 0
Inside loop: x = 1
Inside loop: x = 2
Inside loop, after CONTINUE: x = 3
Inside loop: x = 3
Inside loop, after CONTINUE: x = 4
Inside loop: x = 4
Inside loop, after CONTINUE: x = 5
After loop: x = 5
=================================================
• PL/SQL: For Loop
• This loop is used when some statements in PL/SQL code block are to be
repeated for a xed number of times.
fi
• When we use the for loop we are supposed to de ne a counter variable
which decides how many time the loop will be executed based on a
starting and ending value provided at the beginning of the loop.
• The for loop automatically increments the value of the counter variable by 1
at the end of each loop cycle.
• The programmer need not have to write any instruction for incrementing or
decrementing value.
• These are some special characteristics of loop in PL/SQL.
•
• Following is the ow of control in a For Loop −
• The initial step is executed rst, and only once. This step allows you to
declare and initialise any loop control variables.
• Next, the condition, i.e., initial_value .. nal_value is evaluated. If it is TRUE,
the body of the loop is executed. If it is FALSE, the body of the loop does
not execute and the ow of control jumps to the next statement just after
the for loop.
• After the body of the for loop executes, the value of the counter variable is
increased or decreased.
• The condition is now evaluated again. If it is TRUE, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition). After the condition becomes FALSE, the FOR-LOOP
terminates.
Image1: This PL/SQL code declares a variable `a` of type number with a
precision of 2. It then enters a `FOR` loop where `a` iterates over the range
from 10 to 20 inclusively. Within the loop, it prints the current value of `a`
concatenated with a message using `dbms_output.put_line`. The loop
iterates from 10 to 20, printing each value of `a`. Finally, the program
completes execution.
Image2: This PL/SQL code declares a variable `a` of type number with a
precision of 2. It then enters a `FOR` loop where `a` iterates over the range
from 20 to 10 inclusively in reverse order, as speci ed by the `REVERSE`
keyword. Within the loop, it prints the current value of `a` concatenated with
a message using `dbms_output.put_line`. The loop iterates from 20 down to
10, printing each value of `a` in reverse order. Finally, the program completes
execution.
========================================
WHILE LOOP
It is an entry controlled loop which means that before entering in a while loop
rst the condition is tested, if the condition is TRUE the statement or a group
of statements get executed and if the condition is FALSE the control will
move out of the while loop.
Image1: This PL/SQL code declares a variable `a` of type number with a
precision of 2 and initializes it to 10. It then enters a `WHILE` loop with the
condition `a < 20`. Within the loop, it prints the current value of `a`
concatenated with a message using `dbms_output.put_line`, and increments
`a` by 1 in each iteration. The loop continues executing as long as the
condition `a < 20` remains true. Once `a` reaches 20 or exceeds it, the loop
terminates, and the program completes execution. Essentially, it prints the
values of `a` from 10 up to (but not including) 20.
========================================
Nested Loop is a Loop inside Loop and PL/SQL supports nested loops that
allows you to have multiple levels of iteration within a program. This is
achieved by placing one or more LOOP statements inside another. Each
nested loop has its own set of loop control statements.
When it comes to coding rules and standards for loops in PL/SQL, it's
essential to ensure readability, maintainability, and performance of your
code. Here are some commonly accepted guidelines:
3. **Use FOR Loops When Possible**: If you know the number of iterations
beforehand, use `FOR` loops. They are more concise and easier to read.
fi
fi
fi
```plsql
FOR i IN 1..10 LOOP
-- Loop body
END LOOP;
```
4. **Avoid Nested Loops**: Excessive nesting of loops can make code hard
to understand and maintain. If possible, refactor nested loops into separate
functions or simplify the logic.
5. **Minimize Loop Body**: Keep the logic within the loop body as concise
as possible. If the loop body becomes too complex, consider refactoring it
into a separate function or procedure.
```plsql
FOR rec IN (SELECT * FROM your_table) LOOP
-- Access elds using rec. eld_name
END LOOP;
```
By following these guidelines, you can write cleaner, more e cient PL/SQL
code with loops that are easier to understand and maintain.
fi
fi
fi
ffi