Sub topic 9
Using CASE in SELECT, WHERE, ORDER BY, GROUP BY and UPDATE
This chapter assumes you can write basic SELECT statements with WHERE and ORDER BY, and that you know how GROUP BY and aggregates such as COUNT and SUM work. It also assumes you know the simple and searched forms of CASE and that NULL means "unknown". The examples use the Oracle HR sample schema (employees).
A CASE expression is not a statement that controls flow. It is an expression that produces one value. Oracle accepts an expression wherever it accepts a value of that data type, and that is why CASE can appear in so many clauses.
Where CASE is allowed
| Clause | What CASE does there | Main caveat |
|---|---|---|
| SELECT list | Computes a derived column | Every branch must return a compatible type |
| WHERE | Builds a value that is compared to something | CASE returns a value, not a condition |
| ORDER BY | Defines a custom sort key | Can be placed on an alias or on the expression |
| GROUP BY | Groups rows by a computed category | The expression is usually repeated, not aliased |
| HAVING | Filters groups using a computed value | Same rule as WHERE |
| UPDATE ... SET | Chooses the new value per row | Add `ELSE column` to keep other rows unchanged |
| Inside aggregates | Counts or sums only some rows | Covered in the next chapter |
Why clause order matters
Oracle does not run the clauses in the order you write them. The logical order explains why some clauses can use a column alias from your SELECT list and others cannot.
An alias such as salary_band is created at the SELECT step. WHERE, GROUP BY and HAVING run before it, so they cannot see the alias. ORDER BY runs after it, so it can.
CASE in the SELECT list
This is the most common use. Each row gets a computed label.
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;Branches are tested from top to bottom, and the first true one wins. A salary of 4000 is below 5000 and also below 10000, but it gets Low because that branch comes first.
You can also use CASE inside another expression, such as a string concatenation:
SELECT first_name || ' ' || last_name || ' - ' ||
CASE WHEN commission_pct IS NULL THEN 'salaried' ELSE 'commissioned' END AS employee_summary
FROM employees;CASE in WHERE
In Oracle SQL (before the BOOLEAN type added in 23ai), a CASE expression cannot stand alone as a condition. It returns a value, so you must compare that value with something. The usual pattern is to return a number or string and test it.
SELECT employee_id,
salary,
commission_pct
FROM employees
WHERE CASE
WHEN commission_pct IS NULL THEN salary
ELSE salary + salary * commission_pct
END > 10000;This filters on total pay, where pay is salary alone for employees without commission and salary plus commission for the others.
A frequent use is an optional filter driven by a bind variable:
SELECT employee_id, department_id
FROM employees
WHERE department_id = CASE
WHEN :dept IS NULL THEN department_id
ELSE :dept
END;When :dept is NULL, the right side equals the row's own department_id, so every row passes. There is one gotcha. A row whose department_id is NULL compares NULL = NULL, which is unknown, so that row is dropped even when no filter was requested. Such rows would be kept by WHERE (:dept IS NULL OR department_id = :dept).
CASE in ORDER BY
Alphabetical or numeric order is often not what a report needs. CASE lets you define a rank for each value and sort by that rank.
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 the vice presidents, then everyone else. The second sort key, employee_id, orders the rows inside each rank. Without it, rows in the same rank would come back in no guaranteed order.
Since ORDER BY runs after SELECT, you may sort by an alias:
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 CASE salary_band WHEN 'High' THEN 1 WHEN 'Medium' THEN 2 ELSE 3 END,
salary DESC;All sort-key branches should return the same data type. Mixing numbers and strings in one CASE raises ORA-00932 or forces an implicit conversion, which can sort values in an unexpected way.
CASE in GROUP BY
To count employees per salary band, group by the CASE expression itself. Oracle does not allow a SELECT alias in GROUP BY (this restriction was relaxed only in recent releases), so you repeat the expression.
SELECT CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band,
COUNT(*) AS headcount
FROM employees
GROUP BY CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END
ORDER BY MIN(salary);The two CASE expressions must match exactly in logic, or Oracle raises ORA-00979 ("not a GROUP BY expression"). Sorting by MIN(salary) puts the bands in ascending order, because alphabetical order would put High first.
To avoid repeating the text, define the expression once in an inline view:
SELECT salary_band, COUNT(*) AS headcount
FROM (SELECT CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees)
GROUP BY salary_band;This version is easier to maintain, because changing a band boundary requires editing one place.
CASE in HAVING
HAVING filters groups after aggregation, so it can test a CASE built from aggregates:
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING CASE
WHEN department_id = 90 THEN AVG(salary) > 15000
ELSE AVG(salary) > 5000
END;Oracle SQL has no boolean value, so the pattern above does not work in versions before 23ai. The portable form returns a number and compares it:
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > CASE WHEN department_id = 90 THEN 15000 ELSE 5000 END;Here the CASE returns a threshold, and the comparison is written outside it.
CASE in UPDATE
CASE lets one UPDATE apply a different change to each row. Without it you would need several statements, one per band.
UPDATE employees
SET salary = CASE
WHEN salary < 5000 THEN salary * 1.10
WHEN salary < 10000 THEN salary * 1.05
ELSE salary
END
WHERE department_id = 50;The WHERE clause limits which rows are touched. The CASE then decides the new value for each of them. The final ELSE salary assigns a row its own current value, so high earners are left unchanged.
You can also use CASE in a SET clause that depends on another column:
UPDATE employees
SET commission_pct = CASE
WHEN job_id = 'SA_REP' AND commission_pct IS NULL THEN 0.10
ELSE commission_pct
END
WHERE department_id = 80;A useful check before running an UPDATE is to turn it into a SELECT that shows old and new values side by side. After the real UPDATE, you can undo it with ROLLBACK while you are still testing.
Choosing between the clauses
- Use SELECT when you need a label or calculated value in the output.
- Use WHERE only when the condition truly depends on a branching rule, and keep in mind the index cost.
- Use ORDER BY for ranks that are not alphabetical or numeric order.
- Use GROUP BY with an inline view when the CASE text is long.
- Use UPDATE when several rules apply to different rows, and always write the ELSE.
Exercise
A query uses UPDATE employees SET commission_pct = CASE WHEN job_id = 'SA_REP' THEN 0.15 END WHERE department_id = 80;. What happens to employees in department 80 whose job is not SA_REP, and how do you fix it?
Show answer
Their commission_pct is set to NULL, because a CASE with no matching WHEN and no ELSE returns NULL. Add ELSE commission_pct so non-matching rows keep their current value: SET commission_pct = CASE WHEN job_id = 'SA_REP' THEN 0.15 ELSE commission_pct END.
Exercise
Write a query that returns each department_id with the number of employees earning at least 10000 and the number earning less, sorted so that departments with the most high earners come first. Which clause cannot use your column aliases?
Show answer
SELECT departmentid, SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) AS highearners, SUM(CASE WHEN salary < 10000 THEN 1 ELSE 0 END) AS otherearners FROM employees GROUP BY departmentid ORDER BY high_earners DESC; ORDER BY may use the alias because it runs after SELECT. WHERE, GROUP BY and HAVING run earlier, so they cannot use the aliases.