Sub topic 11
Using CASE in ORDER BY, GROUP BY, and WHERE
This chapter assumes you know how to write a searched or simple CASE expression, how NULL behaves in comparisons, and how column aliases are scoped. It also assumes you can write a basic GROUP BY query. The examples use two tables: employees(employee_id, first_name, last_name, salary, commission, department_id) and orders(order_id, status).
A CASE expression returns a single value. Anywhere SQL accepts a value, you can put a CASE, so it works in ORDER BY, GROUP BY, and WHERE as well as in the SELECT list. Each clause runs at a different point in the query, and that decides what the CASE can see and what can go wrong.
Why the clause matters
A query is logically evaluated in a fixed order, which is different from the order you write it in.
Two consequences follow:
WHEREandGROUP BYrun beforeSELECT. In standard SQL they cannot see aliases defined in the select list.ORDER BYruns afterSELECT. It can see aliases, though with limits described below.
CASE in ORDER BY
ORDER BY sorts by a value. CASE lets you build that value, so you can sort in an order that neither alphabetical nor numeric sorting gives you.
Custom sort order
Suppose you want 'urgent' orders first, then 'normal', then everything else.
SELECT order_id, status
FROM orders
ORDER BY CASE status
WHEN 'urgent' THEN 1
WHEN 'normal' THEN 2
ELSE 3
END,
order_id;The CASE maps each status to a number, and the database sorts by that number. The second sort key, order_id, orders rows inside each group. The ELSE 3 branch is important. Without it, any other status would produce NULL, and where NULL sorts depends on the database.
Controlling where NULL sorts
Databases disagree about whether NULL sorts first or last. PostgreSQL and Oracle put NULL last in ascending order. MySQL, SQLite, and SQL Server put it first. A CASE key gives the same behavior everywhere:
SELECT first_name, commission
FROM employees
ORDER BY CASE WHEN commission IS NULL THEN 1 ELSE 0 END,
commission DESC;Rows with a commission get key 0 and come first. Rows without one get key 1 and come last. Within the first group, higher commissions come first. Some databases support NULLS LAST directly, but this form works in all of them.
Choosing the sort direction at runtime
ASC and DESC are keywords, not values, so a CASE cannot pick between them. Use two CASE keys instead. Each key is NULL for rows when it is not active, and a column of all NULL values does not change the order.
-- :direction is a bind parameter supplied by the application
SELECT employee_id, salary
FROM employees
ORDER BY CASE WHEN :direction = 'asc' THEN salary END ASC,
CASE WHEN :direction = 'desc' THEN salary END DESC;Keep the branches of one CASE the same data type. If you want to switch between a text column and a numeric column, use separate CASE keys, one for each type.
Sorting by an alias inside an expression
The ORDER BY clause runs after SELECT, so you can sort by an alias on its own:
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;Using the alias inside a larger expression is less portable. ORDER BY CASE band WHEN ... works in MySQL and SQLite. PostgreSQL rejects it, because it allows an output alias only as a bare name in ORDER BY. To stay portable, repeat the full expression or move the alias into a subquery, as shown in the next section.
ORDER BY with grouped or DISTINCT queries
After GROUP BY or SELECT DISTINCT, every ORDER BY expression must be built from grouped columns, aggregates, or select-list items. This is valid because department_id is grouped:
SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id
ORDER BY CASE WHEN department_id IS NULL THEN 1 ELSE 0 END,
department_id;CASE in GROUP BY
Grouping by a CASE turns a continuous or messy column into categories. The standard rule is that the GROUP BY expression must match the one in the SELECT list. The easiest way to guarantee that is to compute the category once in a subquery:
SELECT salary_band,
COUNT(*) AS headcount
FROM (
SELECT CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees
) AS e
GROUP BY salary_band
ORDER BY CASE salary_band
WHEN 'high' THEN 1
WHEN 'medium' THEN 2
ELSE 3
END;The inner query defines salary_band once. The outer query groups by it and sorts the bands from high to low. This avoids copying the long CASE into two clauses, and it avoids the PostgreSQL alias restriction described earlier.
You can also repeat the expression in GROUP BY:
SELECT CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band,
COUNT(*) AS headcount
FROM employees
GROUP BY CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END;This works everywhere, but the two copies must stay identical. If you edit one and forget the other, you get an error or, worse, different groupings than you intended.
Some databases let GROUP BY use the select-list alias directly (GROUP BY salary_band). MySQL, PostgreSQL, and SQLite allow it. Standard SQL, SQL Server, and Oracle do not. If your code must run on more than one database, use the subquery form.
CASE in WHERE
A CASE in WHERE must produce a value that is then compared, or it must be compared to something. WHERE CASE ... END on its own is not a condition in most databases, because CASE returns a value rather than true or false.
Comparing to a value that depends on the row
A common use is a threshold that varies by group:
SELECT employee_id, department_id, salary
FROM employees
WHERE salary > CASE department_id
WHEN 10 THEN 80000
WHEN 20 THEN 60000
ELSE 50000
END;For each row, the CASE picks a threshold, and the row passes if its salary exceeds that threshold.
Choosing which condition to apply
You can also use CASE to switch between conditions, as long as it returns something you then test:
SELECT order_id, status
FROM orders
WHERE CASE
WHEN :show_all = 1 THEN 1
WHEN status = 'urgent' THEN 1
ELSE 0
END = 1;This is valid, but a plain boolean expression says the same thing more clearly and gives the optimizer more to work with:
SELECT order_id, status
FROM orders
WHERE :show_all = 1
OR status = 'urgent';Prefer the boolean form when you can. Use CASE in WHERE when you need to select between values, not when you only need AND and OR.
NULL and the default ELSE
If a CASE in WHERE finds no match and has no ELSE, it returns NULL. A comparison with NULL is neither true nor false, so the row is filtered out. This is easy to miss, because the query runs without error and returns fewer rows than you expected. Write an explicit ELSE that says what should happen to unmatched rows.
Performance
A WHERE condition that wraps an indexed column in an expression usually prevents the database from using the index on that column. WHERE CASE WHEN status = 'urgent' THEN 1 ELSE 0 END = 1 is harder to optimize than WHERE status = 'urgent'. The threshold example above is less affected, because the column salary appears bare on the left and only the right side varies by row. Check the query plan on large tables.
Quick reference
| Clause | Runs | Can see select aliases? | Typical use of CASE |
|---|---|---|---|
| WHERE | Before SELECT | No (standard SQL) | Row-dependent thresholds |
| GROUP BY | Before SELECT | Only in some databases | Bucketing values into categories |
| ORDER BY | After SELECT | Yes, with limits | Custom order, `NULL` placement |
Common mistakes
- Referencing a select alias in WHERE. In standard SQL this fails with an unknown-column error. Repeat the expression or use a subquery.
- Different
CASEtext in SELECT and GROUP BY. The database sees two different expressions and may report that the select item is not grouped. - Mixing result types in one
CASE. A branch returning a number and another returning text can cause a conversion error, or silently convert values, depending on the database. - No
ELSEwhere a default is needed. Unmatched rows becomeNULL, which affects sorting, grouping, and filtering. - Expecting a
CASEto switchASCandDESC. It cannot. Use two sort keys.
Exercise
Write a query on employees that counts employees per department_id and lists departments with a NULL department last, otherwise in ascending order of department_id. Which clause holds the CASE, and why does it not need to appear in the SELECT list?
Show answer
SELECT departmentid, COUNT(*) AS headcount FROM employees GROUP BY departmentid ORDER BY CASE WHEN departmentid IS NULL THEN 1 ELSE 0 END, departmentid; The CASE is in ORDER BY. It does not need to appear in the SELECT list because it is built only from the grouped column department_id, which is allowed after GROUP BY, and ORDER BY can sort by any such expression.
Exercise
This query fails in standard SQL. Explain why, and rewrite it so it works: SELECT employeeid, salary * 12 AS annualsalary FROM employees WHERE annual_salary > 100000;
Show answer
WHERE runs before SELECT, so the alias annualsalary does not exist yet. Either repeat the expression, WHERE salary * 12 > 100000, or define the alias in a subquery: SELECT employeeid, annualsalary FROM (SELECT employeeid, salary * 12 AS annualsalary FROM employees) AS e WHERE annualsalary > 100000;
Exercise
A query uses WHERE CASE department_id WHEN 10 THEN salary > 80000 WHEN 20 THEN salary > 60000 END and runs without error in some databases but returns fewer rows than expected. Name two reasons it can drop rows, and give a portable fix.
Show answer
Rows from any other department match no WHEN and there is no ELSE, so the CASE returns NULL and the row is filtered out. Also, boolean-valued CASE branches are not supported everywhere. A portable fix is to compare a value: WHERE salary > CASE department_id WHEN 10 THEN 80000 WHEN 20 THEN 60000 ELSE 0 END, with an explicit ELSE for the remaining departments.