Sub topic 1
Conditions, Booleans, and NULL
Prerequisites
Assume you know basic SELECT, WHERE, and DML statements. You should also know the structure of an anonymous PL/SQL block, how to declare scalar variables, and how to run a script with DBMS_OUTPUT enabled.
Three Possible Condition Results
A Boolean is a value that represents a logical result. In PL/SQL, a Boolean condition can be:
| Result | Meaning | Effect in `IF` |
|---|---|---|
| `TRUE` | The condition is known to be true | The `THEN` statements run |
| `FALSE` | The condition is known to be false | The `THEN` statements do not run |
| `NULL` | The result is unknown | The `THEN` statements do not run |
The third result is important because Oracle uses NULL for a missing or unknown value. A comparison involving NULL usually produces NULL, not TRUE or FALSE.
For example, if l_bonus is NULL, Oracle cannot determine whether it is greater than 100. The expression l_bonus > 100 therefore evaluates to NULL.
An IF statement runs its THEN branch only when its condition is TRUE. Both FALSE and NULL skip that branch.
DECLARE
l_bonus NUMBER := NULL;
BEGIN
IF l_bonus > 100 THEN
DBMS_OUTPUT.PUT_LINE('Large bonus');
ELSE
DBMS_OUTPUT.PUT_LINE('The condition was not TRUE');
END IF;
IF l_bonus IS NULL THEN
DBMS_OUTPUT.PUT_LINE('The bonus is missing');
END IF;
END;
/The first IF prints The condition was not TRUE. The second IF uses IS NULL, which is the correct way to test whether a value is missing.
How `IF` Treats NULL
This flow shows the key rule.
You can assign a comparison to a Boolean variable, but you cannot display a Boolean by concatenating it with text. Test it with control flow instead.
DECLARE
l_quantity NUMBER := NULL;
l_is_large BOOLEAN;
BEGIN
l_is_large := l_quantity >= 10;
IF l_is_large THEN
DBMS_OUTPUT.PUT_LINE('Quantity is large');
ELSIF l_is_large IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Quantity is unknown');
ELSE
DBMS_OUTPUT.PUT_LINE('Quantity is small');
END IF;
END;
/Here, l_quantity >= 10 becomes NULL, so the ELSIF branch identifies the unknown result.
Practical Rules
- Use ordinary comparisons such as
=,>, or<when both values are known. - Use
IS NULLto find missing values. - Use
IS NOT NULLto require a value before performing calculations. - Remember that an
IFbranch runs only forTRUE. - Treat
NULLas unknown, not as zero, an empty string, or a default value.
Exercise
If l_score NUMBER := NULL, which message is printed by IF l_score >= 60 THEN ... ELSE ... END IF, and how should you test specifically for the missing score?
Show answer
The ELSE message is printed because the comparison evaluates to NULL, not TRUE. Test the missing score with IF l_score IS NULL THEN.