Oracle PL/SQL WHILE LOOP with Example

What is While Loop?

WHILE loop statement works similar to the Basic loop statement except the EXIT condition is at the very beginning of the loop.

It works like an entry-check loop in which execution block will not even be executed once if the condition is not satisfied, as the exit condition is checking before execution part. It does not require keyword 'EXIT' explicitly to exit from the loop since it is validating the condition implicitly each time of the loop.

WHILE <EXIT condition>
 LOOP
<execution block starts>
.
.
.
<execution_block_ends>
 END LOOP; 
Syntax Explanation:

Example 1: In this example, we are going to print number from 1 to 4 using WHILE loop statement. For that, we will execute the following code.

Loops in PL/SQL

DECLARE
a NUMBER :=1;
BEGIN
dbms_output.put_line('Program started');
WHILE (a <= 5) 
LOOP
dbms_output.put_line(a);
a:=a+1;
END LOOP;
dbms_output.put_line(‘Program completed' ); 	
END:
/

Code Explanation:

Summary

Loop WHILE Loop
EXIT Criteria Exit when the check condition returns false
Usage Good to use when the loop count is unknown, and exit is based on some other condition.

 

YOU MIGHT LIKE: