Sub topic 10
Conditional Aggregation for Pivot-Style Summaries
This chapter assumes you can write a basic GROUP BY query, know that aggregates skip NULL inputs, and can read a CASE expression. You will turn rows of a category column into separate output columns, and you will learn the errors that most often break this technique.
The problem: one row per category versus one column per category
A plain grouped query returns one row for each combination of grouping columns. Suppose orders has these rows:
| order_id | customer_id | status | amount |
|---|---|---|---|
| 1 | 10 | paid | 100 |
| 2 | 10 | paid | 50 |
| 3 | 10 | refunded | 30 |
| 4 | 11 | paid | 200 |
Grouping by customer_id, status gives three rows. Often a report needs one row per customer, with a column for each status. This layout is called a pivot, or a cross-tab. Conditional aggregation produces it with standard SQL, and it works in every major database.
The core idea
An aggregate function ignores NULL inputs, and a CASE expression with no ELSE branch returns NULL when no WHEN matches. Together these let you feed an aggregate only the rows you care about.
SELECT customer_id,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_total,
SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refunded_total
FROM orders
GROUP BY customer_id;For each customer, the database forms the group, then evaluates each CASE once per row in that group. A row whose status does not match contributes 0, so it leaves the sum unchanged. The result for the sample data:
| customer_id | paid_total | refunded_total |
|---|---|---|
| 10 | 150 | 30 |
| 11 | 200 | 0 |
Everything is computed in a single scan of the table. The alternative is one query per status joined together, which reads the table several times and is harder to maintain.
Choosing the ELSE value
The ELSE branch changes the result for each aggregate, so choose it deliberately.
| Aggregate | Recommended `ELSE` | Reason |
|---|---|---|
| `SUM` | `0` or omitted | A zero adds nothing. Omitting it gives `NULL` when no row matches. |
| `COUNT(expr)` | omitted (`NULL`) | `COUNT` counts non-`NULL` values, so `ELSE 0` would count every row. |
| `AVG` | omitted (`NULL`) | A zero would be averaged in and lower the result. |
| `MIN` / `MAX` | omitted (`NULL`) | A zero could become the minimum or maximum. |
The difference between SUM with ELSE 0 and SUM without it shows up when a group has no matching rows. With ELSE 0 you get 0. Without it you get NULL. Decide which one your report needs. A 0 says "we looked and found nothing", while NULL says "there was nothing to add". You can also wrap the result in COALESCE(SUM(...), 0).
Counting matching rows
To count rows that meet a condition, make the CASE return any non-NULL value when it matches, and leave out ELSE.
SELECT customer_id,
COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
COUNT(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders,
COUNT(*) AS all_orders
FROM orders
GROUP BY customer_id;Another common form sums a 1 or 0:
SELECT customer_id,
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders
FROM orders
GROUP BY customer_id;Both forms return the same count. The COUNT form relies on NULL being skipped, and the SUM form relies on arithmetic. The SUM form always returns a number, even for an empty set of matches, while the COUNT form also returns 0 in that case. They only differ when a group has zero rows, which cannot happen after GROUP BY unless you aggregate the whole table.
Counting distinct values conditionally
You can place DISTINCT inside the aggregate. This counts each customer once, but only among paid orders:
SELECT COUNT(DISTINCT CASE WHEN status = 'paid' THEN customer_id END) AS paying_customers
FROM orders;The CASE returns NULL for non-paid rows, and COUNT(DISTINCT ...) skips those NULL values.
The FILTER clause
The SQL standard defines a FILTER clause that states the same intent more directly. PostgreSQL (9.4 and later) and SQLite (3.30 and later) support it.
SELECT customer_id,
SUM(amount) FILTER (WHERE status = 'paid') AS paid_total,
SUM(amount) FILTER (WHERE status = 'refunded') AS refunded_total,
COUNT(*) FILTER (WHERE status = 'paid') AS paid_orders
FROM orders
GROUP BY customer_id;One difference matters: with FILTER, a group with no matching rows returns NULL for SUM and 0 for COUNT. If you want 0 for the sum, add COALESCE. MySQL, SQL Server and Oracle do not support FILTER, so the CASE form is the portable choice.
Pivoting by time period
Pivots are most often built over dates. Here each column is one quarter of 2026. This example uses EXTRACT, which PostgreSQL, MySQL and Oracle accept.
SELECT customer_id,
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) BETWEEN 1 AND 3
THEN amount ELSE 0 END) AS q1_total,
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) BETWEEN 4 AND 6
THEN amount ELSE 0 END) AS q2_total,
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) BETWEEN 7 AND 9
THEN amount ELSE 0 END) AS q3_total,
SUM(CASE WHEN EXTRACT(MONTH FROM order_date) BETWEEN 10 AND 12
THEN amount ELSE 0 END) AS q4_total
FROM orders
WHERE order_date >= DATE '2026-01-01'
AND order_date < DATE '2027-01-01'
GROUP BY customer_id;The WHERE clause restricts the year before grouping, so the database discards other years early. The CASE expressions then split the remaining rows by quarter. Keep the year restriction in WHERE and not inside each CASE. Otherwise every row from every year is still read and evaluated.
A summary row for the whole table
Remove GROUP BY and the same pattern gives a single-row dashboard:
SELECT COUNT(*) AS all_orders,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue,
100.0 * SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END)
/ NULLIF(SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), 0)
AS refund_rate_pct
FROM orders;NULLIF(x, 0) returns NULL when x is zero, so the division yields NULL and not a divide-by-zero error. Multiplying by 100.0 first forces decimal arithmetic. Writing 100 could trigger integer division in some databases and truncate the result.
Edge cases and common errors
Unlisted categories fall through
A CASE pivot only reports the categories you wrote. If a new status such as 'pending' appears, it is silently missing from every column. To catch this, add a check column or compare against the total:
SELECT customer_id,
SUM(amount) AS all_amount,
SUM(CASE WHEN status IN ('paid', 'refunded') THEN amount ELSE 0 END) AS covered_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) <> SUM(CASE WHEN status IN ('paid', 'refunded') THEN amount ELSE 0 END);Any row returned by this query points to a customer with an unlisted status.
NULL in the tested column
CASE WHEN status = 'paid' evaluates to unknown when status is NULL, and CASE treats unknown as not matched. A row with a NULL status therefore lands in no column. If you need it in an "other" column, test it explicitly with status IS NULL.
Wrong ELSE for AVG
This query lowers the average, because non-paid rows contribute zeros:
-- Wrong: averages in a 0 for every non-paid order
SELECT AVG(CASE WHEN status = 'paid' THEN amount ELSE 0 END) FROM orders;Omit ELSE so non-paid rows become NULL and are skipped. This returns the average of paid orders only.
SELECT AVG(CASE WHEN status = 'paid' THEN amount END) AS avg_paid FROM orders;Columns are fixed at write time
The output columns are part of the query text. SQL cannot change the number of columns based on the data. If the list of categories changes often, you either generate the query text in application code or pivot in the reporting layer. Some databases offer a PIVOT operator (SQL Server, Oracle), but it still needs the values listed explicitly, and it is not portable.
Data type of the result
SUM of an integer column may return a wider integer type, and SUM of a decimal keeps its scale. Mixing ELSE 0 with a decimal THEN branch is safe, because the CASE result type is the common type of its branches. Mixing a text branch with a numeric one is an error in most databases.
Summary
- Wrap a
CASEin an aggregate to compute a value over only the matching rows of each group. - Use
ELSE 0forSUM, and leave outELSEforCOUNT,AVG,MINandMAX. - Use
FILTER (WHERE ...)where it is supported, andCASEwhere portability matters. - Restrict broad conditions such as the year in
WHERE, then split withCASE. - Verify that the pivot columns cover every category and that
NULLvalues were handled on purpose.
Exercise
A table tickets(agent_id, priority, resolved_at) has priorities 'high', 'normal' and 'low', and resolved_at is NULL for open tickets. Write a query that returns one row per agent with three columns: high_open (count of open high-priority tickets), normal_open, and avg_hours_placeholder is not needed. Instead return open_total (count of all open tickets). Explain why COUNT(CASE WHEN ... THEN 1 ELSE 0 END) would give the wrong answer.
Show answer
SELECT agentid, COUNT(CASE WHEN priority = 'high' AND resolvedat IS NULL THEN 1 END) AS highopen, COUNT(CASE WHEN priority = 'normal' AND resolvedat IS NULL THEN 1 END) AS normalopen, COUNT(CASE WHEN resolvedat IS NULL THEN 1 END) AS opentotal FROM tickets GROUP BY agentid; With ELSE 0, the CASE returns a non-NULL value (0) for every row, and COUNT counts non-NULL values, so each column would equal the total number of tickets for the agent. Without ELSE, non-matching rows give NULL and are skipped. Use SUM(CASE ... THEN 1 ELSE 0 END) if you want the ELSE 0 form.
Exercise
Your pivot query lists the statuses 'paid' and 'refunded'. Next month the application starts writing 'pending'. What happens to the pivot output, and how can you detect it?
Show answer
Rows with 'pending' match no CASE branch, so they add nothing to any pivot column and their amounts silently disappear from the report. Detect it by comparing SUM(amount) with the sum of the pivot columns, for example with a HAVING clause that returns groups where they differ, or by running SELECT DISTINCT status FROM orders to list the values that exist.