Oracle pl sql loop exit tutorial

Pl sql exit loop:

The pl sql loop repeatedly executes a block of statements until it reaches a loop exit. The EXIT and EXIT WHEN statements are used to terminate a loop.

Where:

EXIT: The EXIT statement is used to terminate the loop unconditionally and normally used with IF statement.
EXIT WHEN: The EXIT WHEN statement is used to terminate the loop conditionally. It terminates the loop when the specified condition is true.

PL/SQL LOOP statement syntax with EXIT:

LOOP
   //block of statements
   EXIT;
END LOOP;

PL/SQL LOOP statement syntax with EXIT WHEN:

LOOP
   //block of statements
   EXIT WHEN condition;
END LOOP;

PL/SQL LOOP statement example with EXIT:

DECLARE  
  num NUMBER := 1;  
BEGIN  
  LOOP    
    DBMS_OUTPUT.PUT_LINE(num);   
    IF num = 10 THEN
      EXIT;
    END IF;
    num := num+1;
  END LOOP;  
END;

Output:

1
2
3
4
5
6
7
8
9
10

PL/SQL LOOP statement example with EXIT WHEN:

DECLARE  
  num NUMBER := 1;  
BEGIN  
  LOOP    
    DBMS_OUTPUT.PUT_LINE(num);   
    EXIT WHEN num = 10;
    num := num+1;
  END LOOP;  
END;

Output:

1
2
3
4
5
6
7
8
9
10