WHILE

WHILE is a control flow statement in SQL that allows a part of the code to be executed repeatedly based on a specified Boolean condition. The WHILE loop continues executing the block of code it encompasses until the condition evaluates to 'false'.

Example

SET @number = 0;
WHILE @number < 5 DO
SET @number = @number + 1;
SELECT @number;
END WHILE;

Output

1
2
3
4
5

Explanation

In the example provided, a variable @number is initialized as 0. The WHILE loop continues executing the statements within as long as @number is less than 5. Inside the loop, @number is incremented by 1 with each iteration. Consequently, the SQL script outputs the numbers from 1 to 5, inclusively.

Example

DECLARE @intCounter INT
SET @intCounter = 1
WHILE (@intCounter <= 10)
BEGIN
PRINT @intCounter
SET @intCounter = @intCounter + 1
END

Output

1
2
3
4
5
6
7
8
9
10

Explanation

The above SQL script initializes an integer counter and uses a WHILE loop to print the numbers from 1 to 10 incrementally. The loop continues until @intCounter is greater than 10.

Example

DECLARE
num NUMBER := 1;
BEGIN
WHILE num <= 5 LOOP
DBMS_OUTPUT.PUT_LINE(num);
num := num + 1;
END LOOP;
END;
/

Output

1
2
3
4
5

Explanation

In the provided code example, an initial variable named num is declared and set to 1. The WHILE loop starts and checks if num is less than or equal to 5. If it is true, it outputs the value of num and then increments num by 1. This cycle continues until num is greater than 5, causing the WHILE condition to fail and thus terminating the loop. The output, therefore, consists of number 1 to 5, each on a new line.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.