Sub topic 3
Choosing Between Branches with ELSE and ELSIF
This chapter assumes you can write a basic IF ... THEN ... END IF statement and run an anonymous block with DBMS_OUTPUT enabled. It also assumes you know that a condition evaluates to TRUE, FALSE, or NULL. Here you will learn how ELSE and ELSIF extend a single decision into a choice between several branches. You will also learn the errors that appear when you write those chains.
IF-THEN-ELSE: exactly one of two branches
A plain IF-THEN runs its statements when the condition is TRUE and does nothing otherwise. Adding ELSE gives you a second branch. The ELSE branch runs whenever the condition is not TRUE, which means FALSE or NULL.
DECLARE
l_balance NUMBER := 250;
BEGIN
IF l_balance >= 0 THEN
DBMS_OUTPUT.PUT_LINE('Account in credit');
ELSE
DBMS_OUTPUT.PUT_LINE('Account overdrawn');
END IF;
END;
/With l_balance set to 250, the block prints Account in credit. Exactly one branch runs. Control then continues after END IF.
IF-ELSIF-ELSE: several branches, one winner
When you have more than two outcomes, add ELSIF branches between IF and ELSE. Oracle evaluates the conditions from top to bottom. It runs the statements of the first branch whose condition is TRUE, then skips the rest of the chain without evaluating the remaining conditions.
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;
/This prints Grade: C. The score 72 fails the first two tests and passes the third. The ELSE branch is never reached.
The syntax rules are short:
- The keyword is spelled
ELSIF, with no second E.ELSEIFandELSE IFare different things, covered below. - Each
ELSIFneeds its ownTHEN. - The whole chain ends with a single
END IF;, however manyELSIFbranches it has. ELSEis optional. If present, it must be last.
The following diagram shows the path Oracle takes through the grade example.
Order matters
Because the first TRUE condition wins, the sequence of your ELSIF branches is part of the logic. The most common mistake is putting a broad condition before a narrow one.
DECLARE
l_score NUMBER := 95;
l_grade VARCHAR2(1);
BEGIN
IF l_score >= 70 THEN
l_grade := 'C';
ELSIF l_score >= 80 THEN
l_grade := 'B';
ELSIF l_score >= 90 THEN
l_grade := 'A';
ELSE
l_grade := 'F';
END IF;
DBMS_OUTPUT.PUT_LINE('Grade: ' || l_grade);
END;
/This block compiles and runs without any error, and it prints Grade: C for a score of 95. The first condition is TRUE for every score of 70 or more, so the later branches are unreachable. Oracle does not warn you about this, because it cannot know that one condition contains another.
Two habits prevent the problem:
- For ranges that run in one direction, order the tests from the most restrictive to the least restrictive (highest threshold first for
>=, lowest first for<=). - When conditions are mutually exclusive, such as
l_status = 'A'andl_status = 'I', order does not affect correctness. Put the most common case first so the chain usually stops sooner, and clarity is the only other consideration.
What the ELSE branch really means
ELSE means "no earlier condition was TRUE". It does not mean "the opposite condition was FALSE". The difference appears with NULL, because a comparison with NULL yields NULL, which is not TRUE.
DECLARE
l_qty NUMBER := NULL;
BEGIN
IF l_qty > 0 THEN
DBMS_OUTPUT.PUT_LINE('In stock');
ELSE
DBMS_OUTPUT.PUT_LINE('Out of stock');
END IF;
END;
/The block prints Out of stock, even though a NULL quantity is not known to be zero. If missing data needs separate handling, test for it first with IS NULL:
DECLARE
l_qty NUMBER := NULL;
BEGIN
IF l_qty IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Quantity unknown');
ELSIF l_qty > 0 THEN
DBMS_OUTPUT.PUT_LINE('In stock');
ELSE
DBMS_OUTPUT.PUT_LINE('Out of stock');
END IF;
END;
/Placing the IS NULL test first is safe because IS NULL always returns TRUE or FALSE, never NULL. It also guarantees that the later comparisons only see non-NULL values.
Leaving out the ELSE
An IF chain without an ELSE is legal. If no condition is TRUE, no branch runs and execution continues after END IF.
DECLARE
l_temp NUMBER := 21;
BEGIN
IF l_temp > 30 THEN
DBMS_OUTPUT.PUT_LINE('Hot');
ELSIF l_temp < 5 THEN
DBMS_OUTPUT.PUT_LINE('Cold');
END IF;
DBMS_OUTPUT.PUT_LINE('Done');
END;
/The block prints only Done. This silent behavior is a design choice, so decide it on purpose. If the chain is supposed to cover every possible value, add an ELSE that raises an error or logs the unexpected input. Otherwise a value you did not anticipate passes through unnoticed. The CASE statement, covered in a later chapter, behaves differently here: it raises an exception when nothing matches and no ELSE exists.
ELSIF versus ELSE IF
Many programmers who know other languages write ELSE IF. In PL/SQL this is not a synonym for ELSIF. It opens a new, nested IF inside the ELSE branch, and that inner statement needs its own END IF.
DECLARE
l_n NUMBER := 5;
BEGIN
IF l_n < 0 THEN
DBMS_OUTPUT.PUT_LINE('Negative');
ELSE
IF l_n = 0 THEN
DBMS_OUTPUT.PUT_LINE('Zero');
ELSE
DBMS_OUTPUT.PUT_LINE('Positive');
END IF;
END IF;
END;
/This is valid and prints Positive, but it needs two END IF; lines. If you write ELSE IF and only one END IF;, the block fails to compile, usually with PLS-00103: Encountered the symbol ... pointing near the end of the block. When you see that error after editing a chain, count your IF and END IF keywords. Each ELSIF is part of the same statement, while each ELSE IF starts a new one.
For a flat list of alternatives, ELSIF is shorter and easier to read. Use nested IF when the inner decision applies only to one branch.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| Later branch never runs, no error | A broader condition appears earlier in the chain | Reorder so narrow conditions come first |
| `PLS-00103` near `END` or `;` | `ELSE IF` used with a single `END IF`, or a missing `THEN` | Use `ELSIF`, or add the extra `END IF` |
| `ELSE` runs when data is missing | Condition evaluated to NULL | Test `IS NULL` in the first branch |
| Unexpected input is ignored | No `ELSE` on a chain meant to be exhaustive | Add an `ELSE` that raises or logs |
| `PLS-00103` on `ELSEIF` | Misspelled keyword | Write `ELSIF` |
Combining conditions inside a branch
Each branch condition can use AND, OR, and NOT, so a chain can express more than a single comparison. Keep each condition small. If a branch needs a condition spanning several lines, consider assigning the parts to well-named Boolean variables first.
DECLARE
l_age PLS_INTEGER := 17;
l_has_id BOOLEAN := TRUE;
BEGIN
IF l_age >= 18 AND l_has_id THEN
DBMS_OUTPUT.PUT_LINE('Entry allowed');
ELSIF l_age >= 18 THEN
DBMS_OUTPUT.PUT_LINE('Show ID first');
ELSE
DBMS_OUTPUT.PUT_LINE('Too young');
END IF;
END;
/This prints Too young. A Boolean variable can appear directly as a condition, as l_has_id does here. You do not need to write l_has_id = TRUE.
Exercise
A block uses IF l_amt >= 100 THEN l_fee := 0; ELSIF l_amt >= 500 THEN l_fee := -10; ELSE l_fee := 5; END IF; to give a discount of 10 on orders of 500 or more. For lamt = 600, which value does lfee get, and how do you fix the chain?
Show answer
lfee gets 0, because 600 >= 100 is TRUE and the chain stops there. The >= 500 branch can never run. Reorder the branches so the narrower condition comes first: `IF lamt >= 500 THEN lfee := -10; ELSIF lamt >= 100 THEN lfee := 0; ELSE lfee := 5; END IF;`
Exercise
In the block DECLARE l_x NUMBER := NULL; BEGIN IF l_x = 1 THEN DBMS_OUTPUT.PUT_LINE('one'); ELSIF l_x <> 1 THEN DBMS_OUTPUT.PUT_LINE('not one'); ELSE DBMS_OUTPUT.PUT_LINE('other'); END IF; END;, what is printed, and why?
Show answer
It prints other. Both l_x = 1 and l_x <> 1 evaluate to NULL when l_x is NULL, so neither branch is TRUE and the ELSE branch runs.