Sub topic 3
Choosing Between Branches with ELSE and ELSIF
This chapter assumes that you can write an anonymous PL/SQL block, declare and assign variables, and use basic SQL conditions. It also assumes that DBMS_OUTPUT is enabled in your SQL tool.
An IF statement runs a group of statements only when its condition evaluates to TRUE. Add ELSE when you need a fallback branch. Add ELSIF when you need to test more conditions in order.
Adding an ELSE branch
The ELSE branch runs when the IF condition is not TRUE. This includes both FALSE and NULL.
DECLARE
l_score NUMBER := 58;
BEGIN
IF l_score >= 60 THEN
DBMS_OUTPUT.PUT_LINE('Pass');
ELSE
DBMS_OUTPUT.PUT_LINE('Fail');
END IF;
END;
/The condition l_score >= 60 is FALSE, so the block prints Fail. An IF statement must end with END IF;. The semicolon belongs after END IF.
A condition involving NULL also does not select the IF branch:
DECLARE
l_score NUMBER := NULL;
BEGIN
IF l_score >= 60 THEN
DBMS_OUTPUT.PUT_LINE('Pass');
ELSE
DBMS_OUTPUT.PUT_LINE('No passing score');
END IF;
END;
/Comparing a value with NULL produces NULL, not TRUE or FALSE. Since the IF branch requires TRUE, PL/SQL runs ELSE. Test missing values explicitly with IS NULL or IS NOT NULL.
Testing several alternatives with ELSIF
Use ELSIF when the alternatives depend on different conditions. PL/SQL evaluates conditions from top to bottom and runs only the first branch whose condition is TRUE.
DECLARE
l_score NUMBER := 72;
l_grade VARCHAR2(1);
BEGIN
IF l_score >= 90 THEN
l_grade := 'A';
ELSIF l_score >= 80 THEN
l_grade := 'B';
ELSIF l_score >= 70 THEN
l_grade := 'C';
ELSE
l_grade := 'F';
END IF;
DBMS_OUTPUT.PUT_LINE('Grade: ' || l_grade);
END;
/The score is also less than 80, but that comparison is never relevant after l_score >= 70 becomes true. The order matters. Put more specific or higher-priority conditions first.
| Construct | Purpose | If no condition is TRUE |
|---|---|---|
| `IF` | Test one condition | Do nothing after the statement |
| `IF ... ELSE` | Choose between two paths | Run `ELSE` |
| `IF ... ELSIF ... ELSE` | Choose among ordered paths | Run `ELSE`, if present |
How branch selection works
You can place multiple statements in each branch. Keep related actions together, and avoid repeating the same action in several branches when a variable can hold the selected result.
Exercise
What does this block print, and why? DECLARE l_value NUMBER := NULL; BEGIN IF l_value = 0 THEN DBMS_OUTPUT.PUT_LINE('Zero'); ELSIF l_value > 0 THEN DBMS_OUTPUT.PUT_LINE('Positive'); ELSE DBMS_OUTPUT.PUT_LINE('Other'); END IF; END; /
Show answer
It prints Other. Both comparisons with NULL evaluate to NULL, so neither condition is TRUE. The ELSE branch runs.