Sub topic 11
Using CASE in ORDER BY, GROUP BY, and WHERE
Assume you know basic SELECT, WHERE, GROUP BY, COUNT, and SUM queries. This chapter focuses on using CASE to classify rows, control sort order, and filter computed categories.
CASE returns a value based on conditions. Because it is an expression, you can place it wherever SQL accepts an expression, including SELECT, ORDER BY, GROUP BY, and sometimes WHERE.
Custom sorting with CASE
Alphabetical sorting does not always match business priority. For example, an order status might need this order:
urgentnormal- every other status
A CASE expression can convert each status into a numeric sort key:
SELECT order_id, status
FROM orders
ORDER BY CASE status
WHEN 'urgent' THEN 1
WHEN 'normal' THEN 2
ELSE 3
END,
order_id;The database sorts by the result of CASE. It then uses order_id to make the order stable when two rows have the same priority.
You can also sort by a computed column alias when your SQL dialect allows it:
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;Use a CASE expression directly when the sort rule is custom or when you want the rule to be visible at the point of use.
Grouping by a computed category
You can group rows by a category produced by CASE. Suppose salaries should be grouped into bands:
SELECT CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band,
COUNT(*) AS employee_count
FROM employees
GROUP BY CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END;The CASE expression appears twice because many SQL systems do not allow a SELECT alias in the same query block's GROUP BY. A subquery can avoid repeating it:
SELECT salary_band, COUNT(*) AS employee_count
FROM (
SELECT CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees
) AS classified
GROUP BY salary_band;The inner query creates the category. The outer query groups by that named result.
| Goal | Useful CASE location |
|---|---|
| Set a custom row order | `ORDER BY` |
| Create groups from ranges or labels | `GROUP BY` |
| Filter rows by a computed category | `WHERE` in an outer query |
Filtering computed categories
Standard SQL generally does not let WHERE refer to an alias created in the same SELECT list:
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;This may fail because WHERE is logically evaluated before the SELECT list creates annual_salary. Define the alias in a subquery instead:
SELECT employee_id, annual_salary
FROM (
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
) AS e
WHERE annual_salary > 100000;The same pattern works for a CASE category:
SELECT employee_id, salary_band
FROM (
SELECT employee_id,
CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees
) AS classified
WHERE salary_band = 'high';You can also put the full CASE expression directly in WHERE, but that repeats the logic and makes later changes easier to miss.
Common errors
- Do not confuse
WHEREwithHAVING. UseWHEREto filter individual rows before grouping. UseHAVINGto filter groups after aggregation. - Make sure every
CASEbranch returns compatible types. Returning text in one branch and a number in another can cause an error or implicit conversion. - Remember that an omitted
ELSEreturnsNULL. That can create an unexpected group or exclude rows from comparisons. - Check whether your database permits aliases in
GROUP BYorORDER BY.ORDER BYcommonly does;WHEREgenerally does not.
Exercise
Write a query that lists orders with urgent orders first, normal orders second, and all other orders last. Within each priority, sort by order_id.
Show answer
SELECT orderid, status FROM orders ORDER BY CASE status WHEN 'urgent' THEN 1 WHEN 'normal' THEN 2 ELSE 3 END, orderid;