PL/SQL If Statement
PL/SQL supports the programming language features like conditional statements and iterative statements. PL/SQL IF statement check condition and transfer the execution flow on that matched block depending on a condition. IF statement execute or skip a sequence of one or more statements. PL/SQL IF statement four different type,
- IF THEN Statement
- IF THEN ELSE Statement
- IF THEN ELSIF Statement
- Nested IF THEN ELSE Statement
IF-THEN statement:
IF THEN Statement Syntax:
IF condition
THEN
Statement: {It is executed when condition is true}
END IF;
This syntax is used when you want to execute statements only when condition is TRUE.
For 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.
IF-THEN-ELSE statement:
IF-THEN-ELSE statement Syntax:
IF condition
THEN
{...statements to execute when condition is TRUE...}
ELSE
{...statements to execute when condition is FALSE...}
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.
IF-THEN-ELSIF statement:
IF-THEN-ELSIF statement Syntax:
IF condition1
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
END IF;
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.
Nested IF THEN ELSE Statement:
Nested IF THEN ELSE Statement Syntax:
IF condition1
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
ELSE
{...statements to execute when both condition1 and condition2 are FALSE...}
END IF;
For Example,
DECLARE
gender CHAR(20) := 'female';
result CHAR(20) := 'second';
BEGIN
IF ( gender = 'male' ) THEN
DBMS_OUTPUT.PUT_LINE('Gender Male Record Skip!');
ELSE
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 IF;
END;
/
Result
Second Class
PL/SQL procedure successfully completed.