Sub topic 4
How CASE picks a branch: first match, ELSE and no ELSE
This chapter assumes you can write basic SELECT statements with WHERE and ORDER BY, and that you know what NULL means in SQL. You should also have seen the simple and searched CASE forms from the previous chapters. Here the focus is the rule Oracle follows to choose one result, and what happens when no branch qualifies.
The evaluation rule
A CASE expression returns exactly one value for each row. Oracle checks the WHEN branches from top to bottom. It returns the result of the first branch that matches and ignores every branch after it. If no branch matches, Oracle returns the ELSE result. If there is no ELSE, it returns NULL.
The same rule applies to both forms:
- Simple CASE compares one expression to each WHEN value for equality.
- Searched CASE tests each WHEN condition and picks the first one that is true.
This decision is made independently for every row. One row can take the second branch while the next row falls through to ELSE.
First match wins
Only the first matching branch counts, even when later branches would also be true. This makes the order of branches part of the logic.
Here is a searched CASE that assigns salary bands:
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;A salary of 3000 satisfies both salary < 5000 and salary < 10000. It gets 'Low' because the < 5000 branch comes first. The second branch never has to say salary >= 5000 AND salary < 10000, because any row that reaches it has already failed the first test.
If you reverse the first two branches, the result changes:
SELECT salary,
CASE
WHEN salary < 10000 THEN 'Medium'
WHEN salary < 5000 THEN 'Low'
ELSE 'High'
END AS broken_band
FROM (SELECT 3000 AS salary FROM dual
UNION ALL SELECT 7000 FROM dual
UNION ALL SELECT 12000 FROM dual);| SALARY | BROKEN_BAND |
|---|---|
| 3000 | Medium |
| 7000 | Medium |
| 12000 | High |
Every salary below 10000 is caught by the first branch, so 'Low' can never be returned. Oracle raises no error and no warning for an unreachable branch. The query runs and returns wrong data.
The practical rule: order branches from the most specific condition to the most general. For numeric ranges, order them in one direction, either ascending or descending, and do not mix directions.
Overlapping conditions
Overlap is useful when it is deliberate. Suppose a rule says managers in department 90 are 'Executive', and everyone else in department 90 is 'Staff':
SELECT employee_id,
department_id,
job_id,
CASE
WHEN department_id = 90 AND job_id LIKE '%VP' THEN 'Executive'
WHEN department_id = 90 THEN 'Staff'
ELSE 'Outside department 90'
END AS category
FROM employees;The second branch is shorter because the first one has already removed the VPs. Writing it this way is correct, but add a comment if the next reader may reorder the branches.
Evaluation stops at the first match
Oracle uses short-circuit evaluation for CASE. It evaluates a WHEN condition only if no earlier branch matched, and it evaluates a THEN result only for the branch that was chosen. You can use this to protect an expression that would otherwise fail:
SELECT employee_id,
CASE
WHEN commission_pct = 0 OR commission_pct IS NULL THEN NULL
ELSE salary / commission_pct
END AS salary_per_commission_point
FROM employees;When the first branch matches, the division in ELSE is not computed for that row.
The guard has limits. A condition that the optimizer can decide before the query runs, such as one made only of literals, may be evaluated early. A column-based guard like the one above behaves as described. Do not use CASE to hide an error that comes from a constant expression. If a division by zero is possible, guard the divisor with the same column you divide by, or use NULLIF (covered later in this tutorial).
ELSE: the default result
ELSE supplies the value for rows that match no branch. It is optional, but leaving it out has a specific consequence.
SELECT employee_id,
department_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 50 THEN 'Shipping'
ELSE 'Other'
END AS department_label
FROM employees;With the ELSE, an employee in department 80 gets 'Other'. Remove the ELSE line and the same employee gets NULL.
No ELSE means NULL
In a SQL query, a CASE expression with no matching branch and no ELSE returns NULL. It does not raise an error. This is the same as writing ELSE NULL explicitly.
SELECT employee_id,
department_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 50 THEN 'Shipping'
END AS department_label
FROM employees
WHERE department_id IN (10, 80);Employees in department 10 show 'Administration'. Employees in department 80 show an empty value, which is NULL. The risk is quiet data loss. A NULL label can drop out of later comparisons, be skipped by NOT IN, or show up as a blank in a report with no hint that a branch was missing.
Write the ELSE even when you think every case is covered. Choose its value on purpose:
- Use a visible marker such as
'UNMAPPED'when new data values should be noticed. - Use
ELSE NULLwhen NULL is the correct answer, so the next reader knows it was a decision. - Use the original column, for example
ELSE salary, when unmatched rows should stay unchanged.
The last choice matters in UPDATE statements:
UPDATE employees
SET salary = CASE
WHEN salary < 5000 THEN salary * 1.10
WHEN salary < 10000 THEN salary * 1.05
ELSE salary
END
WHERE department_id = 50;If you left out ELSE salary, every row with a salary of 10000 or more would be set to NULL. If the column has a NOT NULL constraint, the UPDATE would fail instead. In either case, the ELSE decides what happens to rows you did not mean to change.
Simple CASE and the equality test
A simple CASE tests equality only, one WHEN value after another, in order. It cannot express <, >, BETWEEN or LIKE. Use a searched CASE for those. Both forms share the first-match rule, so the order of values matters when the same value appears twice:
SELECT CASE 10
WHEN 10 THEN 'first'
WHEN 10 THEN 'second'
ELSE 'none'
END AS result
FROM dual;This returns first. The second branch can never run.
A simple CASE also never matches NULL, because NULL = NULL is not true. A row whose compared expression is NULL moves through every WHEN and ends at ELSE, or at NULL if there is no ELSE. The next chapter covers this in detail. For now, remember that "no match" includes the case where the tested value is NULL.
CASE in PL/SQL: a different no-match rule
The no-ELSE behavior described above is for the CASE expression. PL/SQL also has a CASE statement, which runs statements instead of returning a value and ends with END CASE. When no WHEN matches and there is no ELSE, the statement raises the predefined exception CASE_NOT_FOUND (ORA-06592).
DECLARE
v_grade VARCHAR2(1) := 'C';
v_text VARCHAR2(20);
BEGIN
CASE v_grade
WHEN 'A' THEN v_text := 'Excellent';
WHEN 'B' THEN v_text := 'Good';
END CASE;
DBMS_OUTPUT.PUT_LINE(v_text);
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No branch matched');
END;
/This prints No branch matched. Adding ELSE v_text := 'Unknown'; removes the exception. A CASE expression written inside PL/SQL still follows the SQL rule and returns NULL when nothing matches.
Summary of the rules
| Situation | Result |
|---|---|
| Several branches are true | The first one in text order is used |
| No branch matches, ELSE present | The ELSE result |
| No branch matches, no ELSE (SQL expression) | NULL |
| No branch matches, no ELSE (PL/SQL statement) | CASE_NOT_FOUND exception |
| Same value in two simple CASE branches | Only the first can ever run |
Exercise
The query below is meant to label orders as 'Large' (amount of 1000 or more), 'Medium' (100 to 999) and 'Small' (under 100). It returns 'Small' for every row with an amount of 1000 or more. Why, and how do you fix it? Also, what does it return for a row whose amount is NULL? SELECT orderid, CASE WHEN amount >= 100 THEN 'Medium' WHEN amount >= 1000 THEN 'Large' WHEN amount < 100 THEN 'Small' END AS sizelabel FROM orders;
Show answer
The first branch, amount >= 100, is true for every amount of 1000 or more, so the 'Large' branch is never reached. Those rows get 'Medium', not 'Small'. Fix it by testing the most specific condition first: put WHEN amount >= 1000 THEN 'Large' before the >= 100 branch. Then the second branch can stay as >= 100. For a NULL amount, every comparison is unknown rather than true, so no branch matches. With no ELSE, the expression returns NULL. Adding ELSE 'Small' would be wrong here because it would label NULL amounts as small, so a better choice is a final ELSE 'Unknown' or an explicit WHEN amount IS NULL THEN 'No amount' branch.
Exercise
A DBA runs UPDATE employees SET salary = CASE WHEN department_id = 50 THEN salary * 1.05 END; with no WHERE clause. What happens to employees outside department 50, and what is the smallest change that makes the statement safe?
Show answer
Employees outside department 50 match no branch, and with no ELSE the CASE returns NULL, so their salary is set to NULL (or the statement fails if salary is NOT NULL). The smallest safe change is to add ELSE salary so unmatched rows keep their current value. Adding WHERE department_id = 50 also works and avoids touching other rows at all.