Sub topic 3
Searched CASE: Testing Arbitrary Conditions
What you need before this chapter
This chapter assumes you can write a SELECT with WHERE and ORDER BY. It also assumes you know the basic Oracle types (NUMBER, VARCHAR2, DATE) and that you know NULL means "no value". The examples use the Oracle HR sample schema, mainly the employees table.
The previous chapter covered the simple CASE, which compares one expression with a list of values. That form can only test equality. The searched CASE removes that limit. Each WHEN holds a full condition, so you can use ranges, several columns, AND/OR, LIKE, IN, IS NULL and subqueries.
Syntax
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
[ELSE else_result]
ENDThere is no expression between CASE and the first WHEN. That is how you tell the two forms apart. Each condition is a Boolean test, the same kind you would put in a WHERE clause. Oracle checks the conditions from top to bottom. It returns the result of the first condition that is true and ignores the rest.
A first example: 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 the first condition, so the result is 'Low'. A salary of 7000 fails the first test and passes the second, so the result is 'Medium'. A salary of 15000 fails both tests and reaches ELSE, so the result is 'High'.
The second condition says only salary < 10000. It does not say salary >= 5000, because rows below 5000 never reach it. The order of the branches defines the bands.
The diagram shows "false or unknown" on the failing path. A condition that evaluates to NULL (unknown) is not true, so CASE moves to the next branch. The next chapter covers this rule in detail.
Conditions beyond one column
Because each WHEN holds a full condition, one CASE can mix columns and operators.
SELECT employee_id,
job_id,
department_id,
commission_pct,
CASE
WHEN job_id LIKE 'SA\_%' ESCAPE '\' AND commission_pct IS NOT NULL
THEN 'Sales with commission'
WHEN job_id LIKE 'SA\_%' ESCAPE '\'
THEN 'Sales without commission'
WHEN department_id IN (10, 20, 30)
THEN 'Office'
ELSE 'Other'
END AS staff_type
FROM employees;Points to notice:
- The first branch is more specific than the second, so it comes first. If you swapped them, the specific one would never be reached.
_is a single-character wildcard inLIKE. TheESCAPEclause makes it match a literal underscore, soSA\_%matchesSA_REPandSA_MANbut not a job such asSAX.IS NOT NULLis a valid condition here. A searchedCASEis the standard way to test forNULLinside aCASE.
Other condition forms work the same way.
SELECT employee_id,
hire_date,
CASE
WHEN hire_date < DATE '2000-01-01' THEN 'Before 2000'
WHEN hire_date < DATE '2005-01-01' THEN '2000 to 2004'
ELSE '2005 or later'
END AS hire_period,
CASE
WHEN salary > (SELECT AVG(salary) FROM employees) THEN 'Above average'
ELSE 'At or below average'
END AS vs_company_average
FROM employees;The second CASE uses a scalar subquery. It must return a single value, or Oracle raises an error. Oracle can evaluate such a subquery once and reuse the value, but do not depend on that. Check the execution plan if the query is slow on a large table.
Overlapping conditions and branch order
When conditions overlap, the order decides the outcome. Here is the salary example with the branches reversed.
SELECT employee_id,
salary,
CASE
WHEN salary < 10000 THEN 'Medium'
WHEN salary < 5000 THEN 'Low'
ELSE 'High'
END AS salary_band
FROM employees;This query runs without error, and it is wrong. Every salary below 5000 is also below 10000, so the first branch catches it. The 'Low' branch can never return a value, and Oracle does not warn you.
Two habits help prevent this:
- Order range tests from the narrowest bound to the widest (for
<) or from the widest to the narrowest (for>=), so that each branch can rely on the earlier ones having failed. - If you want branches that do not depend on order, write each range with both bounds, such as
salary >= 5000 AND salary < 10000. This is longer, but each branch can be read alone.
Using the same expression repeatedly
A simple CASE is shorter when you test one expression for equality. A searched CASE is the better choice in these situations:
| Situation | Use |
|---|---|
| One expression compared with a list of constants | Simple `CASE` is shorter |
| Ranges such as `<`, `>=`, `BETWEEN` | Searched `CASE` |
| Several columns in one test | Searched `CASE` |
| `IS NULL`, `LIKE`, `IN`, or subquery tests | Searched `CASE` |
| Different columns tested in different branches | Searched `CASE` |
Any simple CASE can be rewritten as a searched CASE by repeating the expression, for example WHEN department_id = 10. The reverse is not always possible.
Nesting and guarding against errors
A CASE expression can appear in the THEN or ELSE part of another CASE.
SELECT employee_id,
department_id,
commission_pct,
CASE
WHEN department_id = 80 THEN
CASE
WHEN commission_pct >= 0.3 THEN 'Sales: high commission'
ELSE 'Sales: standard commission'
END
ELSE 'Not in sales department'
END AS commission_class
FROM employees;A department 80 employee with a NULL commission makes commission_pct >= 0.3 unknown. The inner CASE then falls to its own ELSE and returns 'Sales: standard commission'. Check that this is what you want. If it is not, add a branch such as WHEN commission_pct IS NULL THEN 'Sales: no commission' at the front of the inner CASE.
Deep nesting is hard to read. If you nest more than two levels, consider whether a flat list of conditions with AND would say the same thing.
You can also use a searched CASE to guard an expression that could fail.
SELECT employee_id,
salary,
commission_pct,
CASE
WHEN commission_pct > 0 THEN salary / commission_pct
ELSE NULL
END AS salary_per_commission_point
FROM employees;The division is protected by the test that comes before it. Oracle evaluates the branches in order and stops at the first true condition. For a guard like this one, that is the behavior you rely on.
Result values and the missing ELSE
Every THEN result and the ELSE result should have a compatible data type. For example, mixing a string and a number raises ORA-00932 or an implicit conversion error. The later chapter on data types covers the exact rules. For now, keep all results in one CASE the same type, and write NULL explicitly where you want no value.
If no condition is true and you wrote no ELSE, the result is NULL. This is a common source of blank cells in reports. Writing an explicit ELSE shows readers that you thought about the leftover rows. If you want blanks, write ELSE NULL.
Oracle also limits how many arguments one CASE can have. The maximum is 255 arguments in total, and each WHEN ... THEN pair counts as two. In practice, a CASE that long should be replaced by a lookup table that you join to.
Checking your work
A quick way to test a CASE is to count rows per result. The counts should add up to the number of rows in the table, and you should see every label you expect.
SELECT CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band,
COUNT(*) AS employees_in_band
FROM employees
GROUP BY CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END
ORDER BY employees_in_band DESC;If a label you expect is missing, the likely cause is a branch that an earlier branch is catching. Oracle requires the GROUP BY to contain the same expression, which is why the CASE appears twice. A later chapter shows how to avoid the repetition.
Exercises
Exercise
Write a query on employees that returns employeeid, salary and a column named taxclass. The class is 'Exempt' when salary is below 3000, 'Standard' when salary is below 8000, 'Elevated' when salary is below 15000, and 'Top' otherwise.
Show answer
SELECT employeeid, salary, CASE WHEN salary < 3000 THEN 'Exempt' WHEN salary < 8000 THEN 'Standard' WHEN salary < 15000 THEN 'Elevated' ELSE 'Top' END AS taxclass FROM employees; The branches go from the lowest bound to the highest, so each later branch relies on the earlier ones having failed.
Exercise
A colleague wrote CASE WHEN salary < 10000 THEN 'Medium' WHEN salary < 5000 THEN 'Low' ELSE 'High' END. Which label never appears, and how do you fix it?
Show answer
'Low' never appears, because every salary below 5000 is also below 10000 and is caught by the first branch. Fix it by putting the narrower test first (WHEN salary < 5000 THEN 'Low' before WHEN salary < 10000 THEN 'Medium'), or by giving the middle branch both bounds (salary >= 5000 AND salary < 10000).
Exercise
What does a searched CASE return for a row when no WHEN condition is true and the CASE has no ELSE?
Show answer
NULL. Add an explicit ELSE to return a different default, or write ELSE NULL to show that the blank is intended.