Sub topic 12
Conditional aggregation with CASE
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries and use GROUP BY with COUNT and SUM. It also assumes you know how a searched CASE expression picks its result, and that NULL means "unknown" and is not equal to anything. The examples use an employees table with employee_id, department_id, salary, commission, and hire_year columns, and an orders table with order_id, status, and amount columns.
The problem conditional aggregation solves
An aggregate function such as SUM or COUNT collapses a group of rows into one value. Sometimes you want several different totals for the same group, and each total should count only some of the rows. For example, you may want each department's headcount and also how many of its employees earn at least 100000.
You could run one query per condition, or join several subqueries together. Both approaches scan the table more than once and make the SQL longer. Conditional aggregation computes all the totals in a single pass. You put a CASE expression inside the aggregate function, so each row contributes to the total only when its condition is true.
The basic pattern
The CASE expression runs once for every row in a group. It turns each row into a value the aggregate can use. Then the aggregate combines those values.
SELECT department_id,
COUNT(*) AS headcount,
SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) AS high_earners
FROM employees
GROUP BY department_id;For each department, COUNT(*) counts every row. The SUM(CASE ...) column adds 1 for each employee with a salary of at least 100000 and 0 for everyone else. The sum of those 1s and 0s is the number of high earners.
The order of work is:
FROMreads the rows ofemployees.GROUP BYputs the rows into groups bydepartment_id.- For each row in each group, the
CASEexpression produces 1 or 0. SUMadds those values within each group.SELECTreturns one row per group.
Three ways to write the condition
There are three common forms. They return the same result when written correctly, but they handle NULL differently, so choose deliberately.
Counting with SUM and 1/0
This is the form shown above. It always returns a number, because ELSE 0 guarantees that no row produces NULL. If a group has no matching rows, the result is 0.
Counting with COUNT and an implicit ELSE NULL
COUNT(expression) counts only the rows where the expression is not NULL. A CASE without an ELSE returns NULL when no condition is true. Combining the two gives a second way to count matching rows.
SELECT department_id,
COUNT(*) AS headcount,
COUNT(CASE WHEN salary >= 100000 THEN 1 END) AS high_earners
FROM employees
GROUP BY department_id;Here the value inside THEN does not matter, as long as it is not NULL. Rows that fail the condition produce NULL and are skipped by COUNT.
A common error is to write COUNT(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END). Now every row produces a non-NULL value, so COUNT counts all of them and you get the same number as COUNT(*).
Summing a column conditionally
You are not limited to counting. Put the column you want to add in the THEN branch to total only some rows.
SELECT department_id,
SUM(salary) AS total_salary,
SUM(CASE WHEN commission IS NOT NULL THEN salary ELSE 0 END) AS salary_of_commissioned
FROM employees
GROUP BY department_id;The IS NOT NULL test is a normal condition inside a searched CASE. Because the branch returns salary or 0, the SUM is never NULL for a group that has at least one row.
Pivoting rows into columns
Conditional aggregation is the standard way to turn row values into columns, which is called a pivot. Suppose you want one row per department with a separate count for each order status. The same technique works for any category column.
SELECT department_id,
SUM(CASE WHEN hire_year = 2022 THEN 1 ELSE 0 END) AS hired_2022,
SUM(CASE WHEN hire_year = 2023 THEN 1 ELSE 0 END) AS hired_2023,
SUM(CASE WHEN hire_year = 2024 THEN 1 ELSE 0 END) AS hired_2024
FROM employees
GROUP BY department_id
ORDER BY department_id;Each output column is a separate aggregate with its own condition. The result has one row per department and one column per year. Employees hired in other years count toward none of these three columns.
The same idea works on the orders table. This query returns the order amount per status in a single row:
SELECT SUM(CASE WHEN status = 'P' THEN amount ELSE 0 END) AS pending_amount,
SUM(CASE WHEN status = 'S' THEN amount ELSE 0 END) AS shipped_amount,
SUM(CASE WHEN status = 'D' THEN amount ELSE 0 END) AS delivered_amount
FROM orders;There is no GROUP BY here, so the whole table is one group and the query returns exactly one row.
The limitation is that you must list every column by hand. If a new status or year appears, the query does not pick it up. Some databases have a PIVOT feature, but it is not standard SQL and it has the same limit, because the column list must be known when the query is written.
Percentages and ratios
You can divide one conditional aggregate by another or by a total. Be careful with integer division and with empty groups.
SELECT department_id,
100.0 * SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END)
/ NULLIF(COUNT(*), 0) AS pct_high_earners
FROM employees
GROUP BY department_id;Two details matter here:
- The literal
100.0makes the arithmetic decimal. In several databases, dividing two integers gives an integer, so3 / 4would be 0. Multiplying by100.0first converts the whole expression to a decimal type. NULLIF(COUNT(*), 0)returnsNULLwhen the count is 0, which avoids a division-by-zero error. A group produced byGROUP BYalways has at least one row, so this guard matters most when you use the pattern withoutGROUP BYon a table that might be empty.
Averages over a subset
AVG ignores NULL values. That makes a CASE without ELSE a clean way to average only some rows.
SELECT department_id,
AVG(salary) AS avg_salary_all,
AVG(CASE WHEN commission IS NOT NULL THEN salary END) AS avg_salary_commissioned
FROM employees
GROUP BY department_id;The second average includes only employees who have a commission. If you wrote ELSE 0 instead, the zeros would be included in the average and would pull it down. For AVG, MIN, and MAX, leaving out ELSE is almost always the correct choice. If a department has no matching rows, the result is NULL, which correctly says "no data" and not "zero".
Edge cases and common errors
An aggregate over no matching rows
SUM returns NULL, not 0, when every input is NULL or there are no input rows. With ELSE 0, rows exist and each contributes 0, so the sum is 0. Without ELSE, a group with no matching rows gives NULL. When you want a number in the report, wrap the aggregate in COALESCE:
SELECT department_id,
COALESCE(SUM(CASE WHEN commission IS NOT NULL THEN salary END), 0) AS commissioned_salary
FROM employees
GROUP BY department_id;NULL inside the condition
A CASE branch fires only when its condition is true. If salary is NULL, then salary >= 100000 is unknown, not true, so the row falls through to ELSE. With ELSE 0 that row adds 0, which is usually what you want. Check that this matches your meaning. A row with an unknown salary is counted in COUNT(*) but not in high_earners, so the two columns together do not say how many employees have low salaries.
Conditional aggregates and WHERE
You could filter with WHERE salary >= 100000 and get a count of high earners. But WHERE removes rows before grouping, so it affects every aggregate in the query. If you also want the total headcount, you need the CASE inside the aggregate. Use WHERE when the condition applies to the entire result, and use CASE inside aggregates when different columns need different conditions.
Filtering on a conditional aggregate
You cannot test an aggregate in WHERE, because the aggregate does not exist yet at that point. Use HAVING, which runs after grouping:
SELECT department_id,
SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) AS high_earners
FROM employees
GROUP BY department_id
HAVING SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) >= 3;The expression is repeated in HAVING because standard SQL does not let HAVING use the alias high_earners. Some databases, such as MySQL and PostgreSQL in certain cases, accept aliases in HAVING or GROUP BY. Repeating the expression works everywhere. Alternatively, put the aggregate in a subquery and filter on its alias in the outer query, as you did with WHERE earlier in this tutorial.
Mixed result types
All branches of a CASE must produce compatible types, and the aggregate then works on the resulting type. SUM(CASE WHEN ... THEN amount ELSE 0 END) is fine when amount is numeric. Writing ELSE 'none' would try to mix text and numbers, which raises an error in most databases.
FILTER as an alternative
PostgreSQL, SQLite, and some other databases support the standard FILTER clause on aggregates. It expresses the same idea more directly:
SELECT department_id,
COUNT(*) AS headcount,
COUNT(*) FILTER (WHERE salary >= 100000) AS high_earners
FROM employees
GROUP BY department_id;FILTER is easier to read, but it is not available in every database, including MySQL and older versions of SQL Server. The CASE form works in all of them, so it is the portable choice.
| Technique | Portable | Handles NULL cleanly | Best for |
|---|---|---|---|
| `SUM(CASE ... THEN 1 ELSE 0 END)` | Yes | Always returns a number | Counts and flags |
| `COUNT(CASE ... THEN 1 END)` | Yes | Skips non-matching rows | Counts |
| `AVG(CASE ... THEN x END)` | Yes | Ignores non-matching rows | Averages, minimums, maximums |
| `COUNT(*) FILTER (WHERE ...)` | No | Skips non-matching rows | Readable queries on supporting databases |
Summary of the rules
- Put the
CASEinside the aggregate, not around it. - Use
ELSE 0withSUMwhen you want a number even for empty matches. - Omit
ELSEwithCOUNT,AVG,MIN, andMAXso that non-matching rows are ignored. - Use
HAVING, notWHERE, to filter on the result. - Multiply by a decimal literal and guard with
NULLIFwhen you compute ratios.
Exercise
A table employees has 10 rows in department 5. Four have a salary of at least 100000, and two have a NULL salary. What do SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) and COUNT(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) return for department 5?
Show answer
The SUM returns 4. The four high earners add 1 each, and the other six rows (including the two with NULL salary, where the condition is unknown) fall through to ELSE and add 0. The COUNT returns 10, because the CASE never returns NULL (ELSE 0 gives every row a non-NULL value), and COUNT counts every non-NULL value. To count only high earners with COUNT, remove the ELSE 0.
Exercise
Write a query that returns, for each department, the percentage of employees who have a commission, as a decimal number, without failing on an empty group.
Show answer
SELECT departmentid, 100.0 SUM(CASE WHEN commission IS NOT NULL THEN 1 ELSE 0 END) / NULLIF(COUNT(), 0) AS pctwithcommission FROM employees GROUP BY departmentid; The 100.0 forces decimal arithmetic, IS NOT NULL is the correct way to test for a missing commission, and NULLIF turns a zero count into NULL so there is no division-by-zero error.
Exercise
You want the average salary of employees hired in 2023, next to the average salary of all employees in the same department, in one query. Which one needs a CASE, and should it have an ELSE?
Show answer
The 2023 average needs the CASE: AVG(CASE WHEN hire_year = 2023 THEN salary END). It should have no ELSE, so that other rows produce NULL and AVG ignores them. With ELSE 0 the zeros would be averaged in and lower the result. The all-employee average is a plain AVG(salary).