Sub topic 10
Conditional aggregation: SUM(CASE ...) and pivoting rows to columns
This chapter assumes you can write simple and searched CASE expressions, and that you know GROUP BY with COUNT and SUM. It also assumes you know that aggregate functions skip NULL values. Examples use the HR sample schema (employees, with department_id, job_id, salary and commission_pct).
The idea
A normal aggregate such as COUNT(*) or SUM(salary) works on every row in a group. Often you want several numbers per group, each over a different subset of rows. For example, you might want a headcount per department plus how many of those people earn at least 10000.
You could run one query per subset and join the results. Conditional aggregation avoids that. You put a CASE expression inside the aggregate, so each row contributes a value only when it meets a condition. The table is read once, and each condition becomes its own output column.
SELECT department_id,
COUNT(*) AS headcount,
SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) AS high_earners,
SUM(CASE WHEN salary < 10000 THEN 1 ELSE 0 END) AS other_earners
FROM employees
GROUP BY department_id
ORDER BY department_id;For each row, the CASE returns 1 or 0. SUM then adds those numbers across the group, which gives a count of the matching rows. The two CASE columns always add up to headcount here, except when salary is NULL (see below).
Three common patterns
Counting with SUM or COUNT
SUM(CASE WHEN cond THEN 1 ELSE 0 END) is the most readable form. It always returns a number, and it returns 0 when no row matches.
COUNT also works, but you must handle the ELSE branch carefully. COUNT(expr) counts non-NULL values, so the "no match" case must produce NULL, not 0:
SELECT department_id,
COUNT(CASE WHEN salary >= 10000 THEN 1 END) AS high_earners
FROM employees
GROUP BY department_id;A CASE without an ELSE returns NULL when no WHEN matches, so this works. If you wrote ELSE 0 here, every row would be counted, because 0 is not NULL. This is one of the most frequent mistakes with this technique.
Summing a value conditionally
You can return the column itself instead of 1. This adds up salary only for rows that meet a condition:
SELECT department_id,
SUM(CASE WHEN job_id LIKE 'SA%' THEN salary END) AS sales_payroll,
SUM(CASE WHEN job_id NOT LIKE 'SA%' THEN salary END) AS other_payroll
FROM employees
GROUP BY department_id
ORDER BY department_id;Here the missing ELSE is deliberate, because SUM ignores NULLs. One side effect: if no row in a group matches, SUM over all-NULL input returns NULL, not 0. Wrap the result in NVL(..., 0) if you want a zero.
Averages and other aggregates
The same approach works for AVG, MIN and MAX. For AVG, leaving out the ELSE is the correct choice, because an ELSE 0 would add zeros to the average:
SELECT department_id,
AVG(CASE WHEN job_id LIKE 'SA%' THEN salary END) AS avg_sales_salary
FROM employees
GROUP BY department_id;Pivoting rows to columns
A pivot turns the distinct values of a column into separate output columns. The data is stored as one row per employee, but a report may want one row per department with one column per job.
Conditional aggregation is the classic way to do this in Oracle SQL. Each output column is one SUM(CASE ...) or COUNT(CASE ...).
SELECT department_id,
COUNT(CASE WHEN job_id = 'SA_REP' THEN 1 END) AS sales_reps,
COUNT(CASE WHEN job_id = 'SA_MAN' THEN 1 END) AS sales_managers,
COUNT(CASE WHEN job_id = 'ST_CLERK' THEN 1 END) AS stock_clerks,
COUNT(*) AS total
FROM employees
GROUP BY department_id
ORDER BY department_id;Each row of the result is one department. The total column counts every row, including jobs that have no column of their own.
Pivoting with a value instead of a count
Suppose you have a table of monthly sales with one row per product per month. You can build a table with one column per quarter:
CREATE TABLE sales_by_month (
product VARCHAR2(20),
month_no NUMBER(2),
amount NUMBER(10,2)
);
INSERT INTO sales_by_month VALUES ('Widget', 1, 100);
INSERT INTO sales_by_month VALUES ('Widget', 4, 150);
INSERT INTO sales_by_month VALUES ('Widget', 5, 50);
INSERT INTO sales_by_month VALUES ('Gadget', 2, 70);
INSERT INTO sales_by_month VALUES ('Gadget', 7, 90);
SELECT product,
SUM(CASE WHEN month_no BETWEEN 1 AND 3 THEN amount ELSE 0 END) AS q1,
SUM(CASE WHEN month_no BETWEEN 4 AND 6 THEN amount ELSE 0 END) AS q2,
SUM(CASE WHEN month_no BETWEEN 7 AND 9 THEN amount ELSE 0 END) AS q3,
SUM(CASE WHEN month_no BETWEEN 10 AND 12 THEN amount ELSE 0 END) AS q4
FROM sales_by_month
GROUP BY product
ORDER BY product;The result:
| PRODUCT | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| Gadget | 70 | 0 | 90 | 0 |
| Widget | 100 | 200 | 0 | 0 |
Here ELSE 0 is used so that empty quarters show 0 instead of NULL.
Limits of the technique
- The output columns are fixed when you write the query. If a new job or quarter appears, the query does not gain a column unless you edit it.
- Each CASE repeats the condition, so a wide pivot is long. Generating the SQL text from a script helps if the list is long.
- Oracle also has a
PIVOTclause (from Oracle 11g) that expresses the same thing more compactly. It also needs the column list written out in advance. The CASE form works in any version and lets you mix counts, sums and arbitrary conditions in one query.
Conditional aggregation and NULL
Two NULL rules decide whether your results are right.
- Aggregates skip NULL inputs.
SUM,AVG,MIN,MAXandCOUNT(expr)ignore NULL values.COUNT(*)counts rows and ignores nothing. - A CASE row that matches no WHEN, with no ELSE, returns NULL.
If the tested column can be NULL, a row can fall into no branch at all. In the earlier headcount query, an employee with a NULL salary fails both salary >= 10000 and salary < 10000. The comparison result is unknown, not true, so the row lands in neither column and the two columns no longer add up to headcount. Add an explicit branch when that matters:
SELECT department_id,
COUNT(*) AS headcount,
SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) AS high_earners,
SUM(CASE WHEN salary < 10000 THEN 1 ELSE 0 END) AS other_earners,
SUM(CASE WHEN salary IS NULL THEN 1 ELSE 0 END) AS no_salary
FROM employees
GROUP BY department_id
ORDER BY department_id;Conditional aggregation in HAVING and with filters
CASE inside an aggregate can also appear in HAVING, which filters groups after aggregation. This keeps only departments where more than half of the staff earn at least 10000:
SELECT department_id,
COUNT(*) AS headcount
FROM employees
GROUP BY department_id
HAVING SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) > COUNT(*) / 2;Do not move the condition into WHERE when you need several different subsets in the same query. A WHERE clause removes rows before any aggregate sees them, so every column would be computed from the same rows. Use WHERE for a condition that applies to the whole query, and CASE for conditions that differ per column.
Percentages and ratios
Because the pieces are ordinary aggregates, you can combine them in arithmetic. Dividing by COUNT(*) gives a share. COUNT(*) is never 0 inside a group, so there is no division by zero here:
SELECT department_id,
ROUND(100 * SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_high
FROM employees
GROUP BY department_id
ORDER BY department_id;If you divide by a conditional count instead, guard against zero with NULLIF(denominator, 0), which turns a zero denominator into NULL and avoids ORA-01476.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `COUNT(CASE ... ELSE 0 END)` | Counts every row | Remove the ELSE, or use `SUM` with 1 and 0 |
| `AVG(CASE ... ELSE 0 END)` | Average is too low | Remove the ELSE so non-matching rows are skipped |
| Selecting a non-grouped column | ORA-00979 | Add it to GROUP BY or aggregate it |
| Mixing data types in the THEN branches, such as `1` and `'none'` | ORA-00932 or ORA-00907-type errors, or an implicit conversion | Make all result branches the same type |
| Ignoring NULL in the tested column | Rows silently drop out | Add an `IS NULL` branch |
Exercise
Using the employees table, write a query that returns one row per departmentid with two columns: `withcommission, the number of employees whose commission_pct is not NULL, and withoutcommission`, the number whose commissionpct is NULL. Use CASE inside aggregates and do not use WHERE.
Show answer
SELECT departmentid, COUNT(CASE WHEN commissionpct IS NOT NULL THEN 1 END) AS withcommission, COUNT(CASE WHEN commissionpct IS NULL THEN 1 END) AS withoutcommission FROM employees GROUP BY departmentid ORDER BY department_id; An equivalent version uses SUM(CASE WHEN ... THEN 1 ELSE 0 END). Do not add ELSE 0 inside COUNT, because 0 is not NULL and every row would be counted.
Exercise
A query uses AVG(CASE WHEN job_id LIKE 'SA%' THEN salary ELSE 0 END) per department. A department has 4 employees, 1 of them in sales earning 8000. What does the query return for that department, and what should it return if you want the average sales salary?
Show answer
It returns 2000, because the sum is 8000 and the ELSE 0 adds three zeros to a group of four rows (8000 / 4). To get the average of sales salaries only, remove the ELSE so non-sales rows become NULL and AVG skips them. The result is then 8000.