Sub topic 12
Conditional Aggregation with CASE
Assume you know basic SELECT, WHERE, GROUP BY, COUNT, and SUM. Conditional aggregation combines an aggregate function with CASE so that one grouped query can calculate several filtered totals.
The basic pattern
CASE can turn a condition into a value. For example, this expression returns 1 for high salaries and 0 for other salaries:
CASE
WHEN salary >= 100000 THEN 1
ELSE 0
ENDSUM can then add those values. The result is a count of rows that meet the condition.
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 employee. The SUM counts only employees whose salary is at least 100,000. Each qualifying row contributes 1; every other row contributes 0.
The same technique works for totals. Return the amount for matching rows and zero for other rows:
SELECT department_id,
SUM(
CASE
WHEN job_title = 'Sales Representative' THEN salary
ELSE 0
END
) AS sales_salary_total
FROM employees
GROUP BY department_id;The query still reads each department group once, but it produces a conditional result inside that group.
Several conditions in one query
You can place multiple CASE expressions in the same SELECT list. This is useful for a report that needs several categories:
SELECT department_id,
COUNT(*) AS headcount,
SUM(CASE WHEN salary < 50000 THEN 1 ELSE 0 END) AS low_earners,
SUM(CASE WHEN salary >= 50000
AND salary < 100000 THEN 1 ELSE 0 END) AS mid_earners,
SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) AS high_earners
FROM employees
GROUP BY department_id;Each CASE is evaluated separately for each employee. The three category counts should add up to headcount, provided salary is never NULL.
If salary can be NULL, none of the comparisons such as salary >= 100000 is true. The ELSE 0 branch prevents that row from being counted. Decide whether that is correct for your report. You might instead need a separate count of employees with missing salaries.
Conditional averages and `NULL`
For an average over only matching rows, return the value for matching rows and NULL otherwise:
SELECT department_id,
AVG(
CASE
WHEN employment_status = 'active' THEN salary
ELSE NULL
END
) AS average_active_salary
FROM employees
GROUP BY department_id;AVG ignores NULL, so inactive employees do not affect the average. This differs from using ELSE 0, which would include zero values and lower the average.
Some databases also support a filtered aggregate syntax, such as SUM(salary) FILTER (WHERE ...). SUM(CASE ...) is more portable across SQL dialects.
How the rows are transformed
The grouped query applies the CASE expression before the aggregate combines the values.
Common errors
- Put the aggregate around the
CASE, not around only one branch. - Include
ELSE 0when counting withSUM; otherwise nonmatching rows produceNULL, whichSUMignores. - Make category conditions non-overlapping when the categories are meant to partition the rows.
- Keep nonaggregated columns in
GROUP BY, according to your database's rules. - Remember that
CASEreturns one result value per row before aggregation.
Exercise
Write a query that groups orders by customer_id and returns the total order count plus the number of orders whose status is 'shipped'.
Show answer
SELECT customerid, COUNT(*) AS totalorders, SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shippedorders FROM orders GROUP BY customerid;