Sub topic 4
How CASE Picks a Branch: First Match, ELSE, and No ELSE
Prerequisites
This chapter assumes that you can write basic Oracle SELECT statements and understand NULL, NUMBER, and VARCHAR2. You should also know the difference between a simple CASE expression and a searched CASE expression.
A CASE expression chooses one result from several alternatives. Oracle evaluates its branches from top to bottom. It returns the result for the first matching branch and then stops evaluating the remaining branches.
First match in a simple CASE
A simple CASE compares one expression with several values:
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;Oracle evaluates department_id against 10, then 20, then 50. When the value is 20, Oracle returns Marketing. It does not test the 50 branch afterward.
The order matters when branches could overlap indirectly through expressions or when you later edit the query. Put the more specific choices before broader choices.
First true condition in a searched CASE
A searched CASE puts a condition after every WHEN:
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;For a salary of 4,000, both conditions are true. Oracle returns Low because the first condition matches. The Medium condition is never used for that row.
If you reverse the conditions, every salary below 10,000 becomes Medium, including salaries below 5,000:
CASE
WHEN salary < 10000 THEN 'Medium'
WHEN salary < 5000 THEN 'Low'
ELSE 'High'
ENDThis is a common logic error. Check overlapping conditions from the most specific or narrowest range to the broadest range.
ELSE and no matching branch
ELSE defines the fallback result when no WHEN branch matches.
SELECT CASE
WHEN 1 = 0 THEN 'Matched'
ELSE 'Fallback'
END AS result
FROM dual;The result is Fallback.
If you omit ELSE and no branch matches, a SQL CASE expression returns NULL:
SELECT CASE
WHEN 1 = 0 THEN 'Matched'
END AS result
FROM dual;The result is NULL, not an error. This can affect calculations, filters, and displayed output. Add an explicit ELSE when an unmatched row should have a meaningful value.
A CASE condition that evaluates to UNKNOWN, often because it involves NULL, does not count as true. Oracle continues to the next branch.
Exercise
What does this expression return when salary is 4,000? CASE WHEN salary < 10000 THEN 'Medium' WHEN salary < 5000 THEN 'Low' ELSE 'High' END
Show answer
It returns Medium because the first condition is true. Oracle stops after the first matching branch.