Sub topic 2
Simple CASE: matching one expression against values
Assume you know basic SELECT statements, aliases, and common Oracle data types. A simple CASE expression compares one expression with several possible values. It returns the result associated with the first matching value.
The basic pattern
CASE expression
WHEN comparison_value_1 THEN result_1
WHEN comparison_value_2 THEN result_2
...
ELSE default_result
ENDThe CASE expression is evaluated once. Oracle then compares it with each WHEN value from top to bottom. The comparison uses equality. When a match is found, Oracle returns that branch's THEN result and stops checking the remaining branches.
For example, this query converts department numbers into readable labels:
WITH employees AS (
SELECT 101 AS employee_id, 10 AS department_id FROM dual
UNION ALL
SELECT 102, 20 FROM dual
UNION ALL
SELECT 103, 99 FROM dual
)
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
ORDER BY employee_id;The result is:
| EMPLOYEE_ID | DEPARTMENT_ID | DEPARTMENT_LABEL |
|---|---|---|
| 101 | 10 | Administration |
| 102 | 20 | Marketing |
| 103 | 99 | Other |
END is required. The alias after END gives the calculated column a name.
How matching works
A simple CASE is useful when all choices depend on the same value:
CASE status_code
WHEN 'N' THEN 'New'
WHEN 'P' THEN 'Processing'
WHEN 'C' THEN 'Complete'
ELSE 'Unknown'
ENDThe WHEN values should be compatible with the type of the expression. For example, compare a number with numbers and a character value with character values. Oracle also requires the possible result values to have compatible data types.
Important edge cases
If you omit ELSE and no WHEN value matches, Oracle returns NULL:
CASE department_id
WHEN 10 THEN 'Administration'
ENDThis returns NULL for every department other than 10.
Also, NULL does not equal anything in ordinary SQL equality comparisons. Therefore, this does not match a null department:
CASE department_id
WHEN NULL THEN 'No department'
ELSE 'Assigned'
ENDTo test for null, use a searched CASE with IS NULL, which is covered in the next chapter.
Exercise
What does this expression return when departmentid is 20, and what does it return when departmentid is 30? CASE department_id WHEN 10 THEN 'A' WHEN 20 THEN 'B' ELSE 'Other' END
Show answer
It returns B for departmentid 20 and Other for departmentid 30.