Recipe · SQL recipes

SUM with CASE WHEN

Use CASE to decide what each row contributes and SUM to add those contributions up. With 1 and 0 you can count the rows that meet a condition.

Query

We want the total number of orders and, in separate columns, how many are shipped, pending and cancelled.

Verified SQL
SELECT COUNT(*) AS orders,
       SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;

Each order contributes exactly 1 to one of the three sums and 0 to the other two. That is why 9 + 6 + 3 = 18, the same total returned by COUNT(*).

Cases that change the result

The same idea works within each group. Here we work out, per customer, how much of the amount comes from shipped orders and how much from pending ones:

SQL
SELECT customer_id,
       COUNT(*) AS orders,
       SUM(CASE WHEN status = 'shipped' THEN total ELSE 0 END) AS total_shipped,
       SUM(CASE WHEN status = 'pending' THEN total ELSE 0 END) AS pending_total
FROM orders
GROUP BY customer_id
ORDER BY customer_id;

Now each row represents a customer. Within that group, each CASE decides whether an order's amount goes into a particular sum.

Common mix-ups with SUM and CASE WHEN

Using COUNT with ELSE 0

Problem version
COUNT(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END)

COUNT(expression) counts non-null values. Both 1 and 0 are known values, so that expression counts every row. For the 1/0 pattern use SUM; if you choose COUNT, the rows that do not qualify must produce NULL.

Leaving out ELSE without considering an empty set of matches

Without ELSE, CASE returns NULL when the condition is false. If no row contributes a known value, SUM can return NULL instead of 0. Use ELSE 0 when zero correctly means “nothing contributed”.

Overlapping categories by accident

Two independent conditional expressions can count the same row if their conditions overlap. That can be correct, but do not assume the columns always split the rows into exclusive groups as they do in the status example.

To lay those aggregations out as a grid, follow the example in PIVOT: turning rows into columns. Define one row per region and one column per channel, and tell a category with no transactions apart from an unknown amount.