pl-sql
  1. pl-sql-for-loop

For Loop - (PL/SQL Control Statements)

A loop is a control structure that allows a set of statements to be executed repeatedly. The For loop is a popular type of loop in PL/SQL programming. It is used to execute a set of statements for a specified number of times.

Syntax

The basic syntax of the For loop in PL/SQL is as follows:

FOR counter_variable IN lower_limit..upper_limit
LOOP
  -- Statements to be executed
END LOOP;

Here, counter_variable is a looping variable that will be used to count the number of times the loop is executed. lower_limit and upper_limit are the lower and upper limits for the loop, respectively.

Example

Let's see an example of the For loop in PL/SQL that calculates the factorial of a given number:

DECLARE
  num NUMBER := 5;
  fact NUMBER := 1;
BEGIN
  FOR i IN 1..num LOOP
    fact := fact * i;
  END LOOP;
  
  DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || fact);
END;

In this example, we have declared a variable num and initialized it to 5. We then declared another variable fact and initialized it to 1. We used a For loop to calculate the factorial of the num variable, which is the product of all positive integers less than or equal to num. The result is output to the console using the DBMS_OUTPUT.PUT_LINE procedure.

Output

The output of the above example will be:

Factorial of 5 is 120

Explanation

In the above example, the For loop starts with the value of i as 1 and continues to execute the loop until the value of i reaches the value of num. In each iteration of the loop, the value of fact is multiplied with the value of i, and the result is stored back in the fact variable. Finally, the DBMS_OUTPUT.PUT_LINE procedure is used to output the result to the console.

Use

The For loop is used to execute a set of statements for a specified number of times. It is commonly used in PL/SQL programming to perform tasks like iterating through collections, calculating totals, and processing records.

Important Points

  • The For loop is a control structure that allows a set of statements to be executed repeatedly.
  • It is used to execute a set of statements for a specified number of times.
  • The For loop uses a looping variable to count the number of times the loop is executed.
  • The lower_limit and upper_limit expressions are evaluated only once when the loop is entered.

Summary

The For loop is a powerful control structure in PL/SQL that allows a set of statements to be executed repeatedly for a specified number of times. It is a popular choice for iterating through collections, calculating totals, and processing records. Understanding how to use the For loop is essential for any PL/SQL programmer.

Published on: