Looping Structures

In PL/SQL, there are several looping structures that you can use to iterate through a set of statements multiple times. Here are the main looping structures in PL/SQL:

1. LOOP :
The 'LOOP' statement creates an unconditional loop.
It continues until an EXIT statement is encountered.
  declare
  a number:= 10;
  begin
  dbms_output.put_line('Normal Loop');
  loop
  dbms_output.put_line(a);
  a:=a+10;
  exit when a>50;
  end loop;
  end;
  / 
OUTPUT :
Normal Loop
10
20
30
40
50
PL/SQL procedure successfully completed.

2. WHILE :
The 'WHILE' loop repeats a sequence of statements as long as a certain condition is true.

  declare
  i number(5);
  begin
  i := 1;
  while (i < 6)
  loop
  i := i+1;
  dbms_output.put_line('the seq is '||i);
  end loop;
  end;
  /
OUTPUT :
the seq is 2
the seq is 3
the seq is 4
the seq is 5
the seq is 6
PL/SQL procedure successfully completed.

3. FOR :
  • The 'FOR' loop is used when you know the number of iterations in advance.
  • It is often used with index variables.
  • 
      declare
      i number(10);
      begin
      for i in 1..5 loop
      dbms_output.put_line('the sequence is '||i);
      end loop;
      end;
      /
    
    OUTPUT :
    the sequence is 1
    the sequence is 2
    the sequence is 3
    the sequence is 4
    the sequence is 5
    PL/SQL procedure successfully completed.

    4. FOR LOOP IN REVERSE:
    
    declare
     i number(3);
     begin
     for i in reverse 5..10 loop
     dbms_output.put_line('the seq is '||i);
     end loop;
     end;
     /
    
    OUTPUT :
    the seq is 10
    the seq is 9
    the seq is 8
    the seq is 7
    the seq is 6
    the seq is 5
    PL/SQL procedure successfully completed.

    5. Nested loop :
    
    declare
    i number(3);
    j number(3);
    begin
    <>
    for i in 3..5 loop
    << inner_loop>>
    for j in 1100..1101 loop
    dbms_output.put_line('outer loop is '||i||' inner loop is '||j);
    end loop inner_loop;
    end loop outer_loop;
    end;
    /
    
    Output :
    outer loop is 3 inner loop is 1100
    outer loop is 3 inner loop is 1101
    outer loop is 4 inner loop is 1100
    outer loop is 4 inner loop is 1101
    outer loop is 5 inner loop is 1100
    outer loop is 5 inner loop is 1101
    PL/SQL procedure successfully completed.


    (PL/SQL - Composite Datatypes)