PL/SQL For – Loop

In Oracle PL/SQL, a FOR loop is used to repeatedly execute a block of code a specified number of times. The basic syntax of a FOR loop is as follows:

FOR … LOOP syntax

FOR loop_variable IN [REVERSE] start_value..end_value 
LOOP
--pl/sql statements
END LOOP;

The loop_variable is a variable that will take on the value of the current iteration, starting with the start_value and ending with the end_value. The optional keyword REVERSE can be used to iterate through the loop in reverse order.

FOR … LOOP example

DECLARE
  i NUMBER:=0;
  start_value NUMBER:=1;
  end_value NUMBER:=5;
BEGIN
DBMS_OUTPUT.PUT_LINE('Start');
	FOR i IN start_value..end_value
	LOOP
		DBMS_OUTPUT.PUT_LINE(' i: ' || i);
	END LOOP;
DBMS_OUTPUT.PUT_LINE('End');
END;

Output

Start
 i: 1
 i: 2
 i: 3
 i: 4 
 i: 5
End

You can also use FOR loop in cursor statement to loop through the result set, for example:

FOR record IN (SELECT * FROM employees) LOOP 
DBMS_OUTPUT.PUT_LINE(record.first_name || ' ' || record.last_name); 
END LOOP;