Sub topic 2
Simple CASE: matching one expression against values
This chapter assumes you can write a basic SELECT with WHERE and ORDER BY. It also assumes you know the common Oracle data types (NUMBER, VARCHAR2, DATE) and that NULL means "unknown or missing". The examples use the Oracle HR sample schema, mainly the employees table.
What a simple CASE does
A simple CASE expression takes one expression, compares it for equality with a list of values, and returns the result attached to the first value that matches. It is an expression, not a statement. It produces a single value, so you can use it anywhere Oracle accepts a value, such as the select list, ORDER BY, or the right-hand side of an UPDATE.
The general form is:
CASE expr
WHEN comparison_expr1 THEN return_expr1
WHEN comparison_expr2 THEN return_expr2
...
[ELSE else_expr]
ENDHere is a complete example:
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;For each row, Oracle takes the value of department_id and compares it with 10, then 20, then 50. It returns the label of the first comparison that is true. If none match, it returns 'Other'. The AS department_label alias names the resulting column.
You can test the mechanics without any table by using DUAL:
SELECT CASE 2
WHEN 1 THEN 'one'
WHEN 2 THEN 'two'
ELSE 'many'
END AS word
FROM dual;This returns two.
The working model
Think of a simple CASE as a series of equality tests that share a left-hand side. Writing CASE department_id WHEN 10 THEN ... means the same as "if department_id = 10 then ...". The = is built in, and you cannot change it.
Three rules follow from this model.
- Branches are tried in the order you write them. The first equal comparison wins, and Oracle ignores later branches even if they would also match.
- Oracle uses short-circuit evaluation. Each
WHENvalue is evaluated only when it is compared withexpr. After a match, Oracle does not evaluate the remainingWHENvalues or their results. This matters when a later branch would raise an error, such as a division by zero, because that branch is never reached. - Without an
ELSE, an unmatched row yieldsNULL. Oracle does not raise an error in the SQL expression.
When no branch matches
Leaving out ELSE is legal, and it produces NULL for unmatched rows:
SELECT employee_id,
department_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
END AS department_label
FROM employees;Employees in any other department get a NULL label. Sometimes that is what you want. More often it hides a missing case, so add an ELSE unless you have a reason to leave it out. An explicit ELSE 'Unknown' makes unmatched rows easy to spot and filter.
Comparing against different kinds of values
The WHEN values can be literals, columns, or other expressions. They do not have to be constants:
SELECT employee_id,
department_id,
manager_id,
CASE department_id
WHEN manager_id THEN 'Same number as manager id'
WHEN 50 THEN 'Shipping'
ELSE 'Neither'
END AS note
FROM employees;Strings work the same way, and the comparison is case-sensitive:
SELECT employee_id,
job_id,
CASE job_id
WHEN 'AD_PRES' THEN 'President'
WHEN 'AD_VP' THEN 'Vice president'
WHEN 'IT_PROG' THEN 'Programmer'
ELSE 'Other role'
END AS job_title
FROM employees;'it_prog' would not match 'IT_PROG'. If the data has mixed case, wrap the tested expression, for example CASE UPPER(job_id) WHEN 'IT_PROG' THEN ....
What a simple CASE cannot do
Because every branch is an equality test, a simple CASE cannot test ranges or use other operators. This does not work:
-- Invalid: a simple CASE cannot contain comparison operators
SELECT CASE salary
WHEN < 5000 THEN 'Low'
ELSE 'Other'
END
FROM employees;Oracle rejects it with a syntax error. For ranges, LIKE, IN, IS NULL or conditions on several columns, use a searched CASE, which is the next chapter's topic.
The simple form also cannot match NULL. CASE commission_pct WHEN NULL THEN ... never matches, because commission_pct = NULL is never true in SQL. The chapter on NULL handling in CASE explains the details and the fix. For now, remember that the simple form is only for values that can be compared with =.
Data type rules
Two sets of types must be compatible.
- The
WHENvalues must be comparable to the tested expression. Oracle converts them implicitly when it can. For example, comparing aNUMBERcolumn to the string'50'usually works, but it relies on implicit conversion, which fails if some string is not a valid number. Write values in the column's own type. - The
THENandELSEresults must be of the same data type family. If the first result is a string, every other result must be convertible to a string. If the first is numeric, Oracle picks the numeric type with the highest precedence among all the results.
This statement fails because one branch returns text and another returns a number:
SELECT CASE department_id
WHEN 10 THEN 'Administration'
ELSE 0
END AS label
FROM employees;Oracle raises ORA-00932: inconsistent datatypes: expected CHAR got NUMBER. The fix is to make the types agree, for example ELSE 'None', or ELSE TO_CHAR(department_id) to keep the department number as text.
Limits and style
- A
CASEexpression can have at most 255 arguments. The tested expression and theELSEeach count as one argument, and eachWHEN ... THENpair counts as two, which allows about 126 branches. If you need more, put the mapping in a lookup table and join to it. - You cannot write the literal
NULLas everyTHENandELSEresult. At least one result must be something other than the bare keywordNULL. - Always end with
END. A missingENDis the most common syntax slip and typically givesORA-00905: missing keyword. - Give the expression a column alias. Without one, the column heading is the entire
CASEtext. - Put the most common values first when the list is long. Because evaluation is sequential and short-circuits, this saves a few comparisons, but readability matters more than speed here.
- Order
WHENvalues deliberately. Duplicate values are legal, but the second one can never be reached.
Using the result
Since the CASE produces a value, you can put it anywhere a value fits. This query sorts by a custom order instead of alphabetically:
SELECT employee_id, job_id
FROM employees
ORDER BY CASE job_id
WHEN 'AD_PRES' THEN 1
WHEN 'AD_VP' THEN 2
ELSE 3
END,
employee_id;The president comes first, then vice presidents, then everyone else ordered by employee_id. A later chapter covers CASE in WHERE, GROUP BY, UPDATE and aggregates in more detail.
Summary of the key points
| Question | Answer |
|---|---|
| What operator does the simple form use? | Equality (`=`) only |
| What happens on a tie between two matching WHENs? | The first one in the text wins |
| What if nothing matches and there is no ELSE? | The result is `NULL` |
| Can it match `NULL`? | No. `WHEN NULL` never matches |
| Can THEN results have different types? | Only if they belong to one convertible family |
Exercise
A query uses CASE department_id WHEN 50 THEN 'Shipping' WHEN 50 THEN 'Warehouse' ELSE 'Other' END. What does an employee in department 50 get, and what does an employee in department 80 get?
Show answer
The employee in department 50 gets 'Shipping', because the first matching WHEN wins and the second WHEN 50 is never reached. The employee in department 80 gets 'Other' from the ELSE branch.
Exercise
Write a query on employees that returns employeeid and a column named tier. Use a simple CASE on jobid to return 'Executive' for 'ADPRES' and 'ADVP', 'Technical' for 'IT_PROG', and 'General' for everything else.
Show answer
SELECT employeeid, CASE jobid WHEN 'ADPRES' THEN 'Executive' WHEN 'ADVP' THEN 'Executive' WHEN 'IT_PROG' THEN 'Technical' ELSE 'General' END AS tier FROM employees;
Exercise
Why does CASE department_id WHEN 10 THEN 'Administration' ELSE 0 END fail, and how do you fix it?
Show answer
The THEN result is text and the ELSE result is a number, so Oracle raises ORA-00932 (inconsistent datatypes). Make both results the same type, for example ELSE 'None' or ELSE TOCHAR(departmentid).