Sub topic 2
Making a Decision with IF-THEN
Assume you know basic SELECT, WHERE, and DML, the structure of an anonymous PL/SQL block, scalar variables, and how to run a script with DBMS_OUTPUT enabled.
An IF-THEN statement runs a group of statements only when a condition evaluates to TRUE. A condition is an expression that produces a Boolean result. In PL/SQL, that result can be TRUE, FALSE, or NULL.
IF condition THEN
statements;
END IF;END IF closes the statement. The semicolon after END IF is required.
How PL/SQL evaluates the condition
PL/SQL does not run the THEN block unless the condition is exactly TRUE.
| Condition result | Does the `THEN` block run? |
|---|---|
| `TRUE` | Yes |
| `FALSE` | No |
| `NULL` | No |
A missing value is represented by NULL. Comparisons involving NULL usually produce NULL, not TRUE or FALSE.
A complete IF-THEN example
This block checks whether an order has items. The message is printed only when l_quantity > 0 is true.
DECLARE
l_quantity PLS_INTEGER := 4;
BEGIN
IF l_quantity > 0 THEN
DBMS_OUTPUT.PUT_LINE('The order contains items.');
END IF;
DBMS_OUTPUT.PUT_LINE('Order check complete.');
END;
/The condition is evaluated first. Because 4 > 0 is true, PL/SQL prints the first message and then continues after END IF.
You can place several statements inside the THEN block:
DECLARE
l_balance NUMBER := 125;
BEGIN
IF l_balance > 0 THEN
DBMS_OUTPUT.PUT_LINE('The account has a positive balance.');
DBMS_OUTPUT.PUT_LINE('It can be used for payment.');
END IF;
END;
/Indenting the statements between THEN and END IF makes the structure easier to check.
Common errors
Use := to assign a value and = to compare values.
DECLARE
l_status VARCHAR2(1) := 'A';
BEGIN
IF l_status = 'A' THEN
DBMS_OUTPUT.PUT_LINE('The record is active.');
END IF;
END;
/Do not test for a missing value with = NULL or <> NULL. Those comparisons produce NULL, so the THEN block does not run. Use IS NULL instead.
DECLARE
l_bonus NUMBER := NULL;
BEGIN
IF l_bonus IS NULL THEN
DBMS_OUTPUT.PUT_LINE('No bonus was assigned.');
END IF;
END;
/Use IF-THEN when the true case needs an action and no action is required otherwise. When both outcomes need different actions, an ELSE branch is clearer.
Exercise
What does this block print, and why? DECLARE l_value NUMBER := NULL; BEGIN IF l_value > 10 THEN DBMS_OUTPUT.PUT_LINE('Large'); END IF; DBMS_OUTPUT.PUT_LINE('Done'); END; /
Show answer
It prints Done. The comparison with NULL evaluates to NULL, not TRUE, so the THEN block is skipped.