Sub topic 3
Searched CASE: testing arbitrary conditions
This chapter assumes that you can write basic SELECT statements with WHERE and ORDER BY, recognize Oracle data types such as NUMBER and VARCHAR2, understand NULL, and use basic aggregate functions.
A searched CASE expression tests conditions instead of comparing one expression with a list of fixed values. It returns the result belonging to the first condition that is true.
Basic syntax
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
ELSE default_result
ENDEach WHEN contains a Boolean condition, such as a comparison, a range check, or several tests joined with AND or OR. The expression returns one value. It does not execute separate SQL statements.
For example, classify employees by salary:
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees
ORDER BY salary;The first condition accepts salaries below 5,000. The second accepts salaries from 5,000 through 9,999.99 because the first condition was false. Every remaining salary receives High.
Conditions are checked from top to bottom
The order of the branches matters. Oracle stops at the first true WHEN condition.
SELECT employee_id,
salary,
CASE
WHEN salary < 10000 THEN 'Under 10000'
WHEN salary < 5000 THEN 'Under 5000'
ELSE '10000 or more'
END AS label
FROM employees;The second branch can never produce Under 5000. A salary of 4,000 already matches the first branch. Put more specific conditions before broader conditions.
ELSE and values that do not match
ELSE is optional. If no WHEN condition is true and there is no ELSE, Oracle returns NULL.
SELECT employee_id,
commission_pct,
CASE
WHEN commission_pct > 0 THEN 'Commissioned'
END AS commission_status
FROM employees;This returns Commissioned for positive commission values and NULL for zero or NULL values. Add an ELSE when an unmatched row needs a clear result.
To test for missing values, use IS NULL rather than = NULL:
SELECT employee_id,
CASE
WHEN commission_pct IS NULL THEN 'Not eligible'
WHEN commission_pct = 0 THEN 'No commission'
ELSE 'Commission eligible'
END AS commission_status
FROM employees;Common uses
A searched CASE can appear anywhere an expression is allowed. Common uses include:
- creating labels in
SELECT - assigning custom priorities in
ORDER BY - grouping rows into categories
- counting conditions with
SUM(CASE ...) - assigning different values in
UPDATE
Keep each result compatible with the other results. Returning text in one branch and a number in another can cause an Oracle datatype error or unwanted implicit conversion.
Exercise
What does this expression return for a salary of 7,500? CASE WHEN salary < 5000 THEN 'Low' WHEN salary < 10000 THEN 'Medium' ELSE 'High' END
Show answer
It returns Medium. The first condition is false, and the second condition is true.