PL/SQL provides control statements to control the flow of execution and loops to execute a block of statements repeatedly. In this blog, we will cover IF statements, nested conditions, and looping mechanisms with examples.
1. IF THEN Statement
The IF THEN statement allows execution of a block only if a condition is true.
Syntax
IF (condition) THEN
statement;
END IF;
Example
DECLARE
no INTEGER(2) := 14;
BEGIN
IF (no = 14) THEN
DBMS_OUTPUT.PUT_LINE('Condition true');
END IF;
END;
/
Result
Condition true
PL/SQL procedure successfully completed.
2. IF THEN ELSE Statement
The IF THEN ELSE statement allows execution of one block if the condition is true, otherwise another block is executed.
Syntax
IF (condition) THEN
statement;
ELSE
statement;
END IF;
Example
DECLARE
no INTEGER(2) := 14;
BEGIN
IF (no = 11) THEN
DBMS_OUTPUT.PUT_LINE(no || ' is same');
ELSE
DBMS_OUTPUT.PUT_LINE(no || ' is not same');
END IF;
END;
/
Result
14 is not same
PL/SQL procedure successfully completed.
3. IF THEN ELSIF Statement
The IF THEN ELSIF statement allows multiple conditions to be checked sequentially.
Syntax
IF (condition-1) THEN
statement-1;
ELSIF (condition-2) THEN
statement-2;
ELSIF (condition-3) THEN
statement-3;
ELSE
statement;
END IF;
Example: (Student grade example)
DECLARE
result CHAR(20) := 'second';
BEGIN
IF (result = 'distinction') THEN
DBMS_OUTPUT.PUT_LINE('First Class with Distinction');
ELSIF (result = 'first') THEN
DBMS_OUTPUT.PUT_LINE('First Class');
ELSIF (result = 'second') THEN
DBMS_OUTPUT.PUT_LINE('Second Class');
ELSIF (result = 'third') THEN
DBMS_OUTPUT.PUT_LINE('Third Class');
ELSE
DBMS_OUTPUT.PUT_LINE('Fail');
END IF;
END;
/
Result
Second Class
PL/SQL procedure successfully completed.
4. Nested IF THEN ELSE Statement
Nested IF THEN ELSE statements are logically similar to IF THEN ELSIF. Each condition is checked inside the else block.
Syntax
IF (condition-1) THEN
statement-1;
ELSE
IF (condition-2) THEN
statement-2;
ELSE
IF (condition-3) THEN
statement-3;
END IF;
END IF;
END IF;

Join the conversation! Your thoughts help the community grow.