Lecture-17 PLSQL CONDITIONAL CONTROL
Lecture-17 PLSQL CONDITIONAL CONTROL
PL/SQL IF Statement
– IF THEN
– IF THEN ELSE
– IF THEN ELSIF
PL/SQL IF THEN STATEMENT
IF condition THEN
statements;
END IF;
The condition is a Boolean expression that always evaluates to TRUE, FALSE, or NULL.
If the condition evaluates to TRUE, the statements after the THEN execute. Otherwise, the
IF statement does nothing.
PL/SQL IF THEN STATEMENT
EXAMPLE
In the following example, the statements between THEN and END IF execute
because the sales revenue is greater than 100,000.
DECLARE n_sales NUMBER := 2000000;
BEGIN
IF n_sales > 100000 THEN
DBMS_OUTPUT.PUT_LINE( 'Sales revenue is greater than 100K ' );
END IF;
END;
PL/SQL IF THEN ELSE
STATEMENT
The IF THEN ELSE statement has the following structure:
IF condition THEN
statements;
ELSE
else_statements;
END IF;
If the condition evaluates to TRUE, then the statements between THEN and ELSE execute.
In case the condition evaluates to FALSE or NULL, the else_statements between ELSE and
END IF executes.
IF THEN ELSE STATEMENT
EXAMPLE
The following example sets the sales commission to 10% if the sales revenue is greater than 200,000. Otherwise, the
sales commission is set to 5%.
DECLARE
n_sales NUMBER := 300000;
n_commission NUMBER( 10, 2 ) := 0;
BEGIN
IF n_sales > 200000 THEN
n_commission := n_sales * 0.1;
ELSE
n_commission := n_sales * 0.05;
END IF;
END;
PL/SQL IF THEN ELSIF
STATEMENT
The following illustrates the structure of the IF THEN ELSIF statement:
IF condition_1 THEN
statements_1
ELSIF condition_2 THEN
statements_2
[ ELSIF condition_3 THEN
statements_3
]
...
[ ELSE
else_statements
]
END IF;
IF THEN ELSIF STATEMENT
EXAMPLE
The following example uses the IF THEN ELSIF statement to set the sales commission based on the sales revenue.
DECLARE
n_sales NUMBER := 300000;
n_commission NUMBER( 10, 2 ) := 0;
BEGIN
IF n_sales > 200000 THEN
n_commission := n_sales * 0.1;
ELSIF n_sales <= 200000 AND n_sales > 100000 THEN
n_commission := n_sales * 0.05;
ELSIF n_sales <= 100000 AND n_sales > 50000 THEN
n_commission := n_sales * 0.03;
ELSE
n_commission := n_sales * 0.02;
END IF;
END;
NESTED IF STATEMENT
IF condition_1 THEN
IF condition_2 THEN
nested_if_statements;
END IF;
ELSE
else_statements;
END IF;