Sub topic 9
Grouping by Expressions Such as `CASE`
This chapter assumes you know SELECT, FROM, WHERE, ORDER BY, NULL, and basic GROUP BY. You will use those features to create groups from calculated values instead of grouping only by stored columns.
Why group by an expression?
GROUP BY creates one group for each distinct grouping key. A grouping key can be a column, several columns, or an expression. An expression is a calculation that produces a value for each input row.
For example, an order table might store an exact amount, but a report might need amount bands:
smallfor amounts below 100mediumfor amounts from 100 through 499.99largefor amounts of 500 or more
A CASE expression can calculate the band for every row. Grouping by that expression then produces one summary row per band.
SELECT
CASE
WHEN amount < 100 THEN 'small'
WHEN amount < 500 THEN 'medium'
ELSE 'large'
END AS amount_band,
COUNT(*) AS order_count,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount
FROM orders
GROUP BY
CASE
WHEN amount < 100 THEN 'small'
WHEN amount < 500 THEN 'medium'
ELSE 'large'
END
ORDER BY
CASE
WHEN amount < 100 THEN 1
WHEN amount < 500 THEN 2
ELSE 3
END;The first WHEN that matches determines the result. Therefore, an amount of 500 is large, while an amount of 499.99 is medium.
The expression must be deterministic
Every row must receive a predictable grouping value. If two rows produce the same value, they belong to the same group. If the expression produces NULL, all rows with that result form one NULL group.
`CASE` and `NULL`
A searched CASE expression has conditions. If no condition matches and there is no ELSE, it returns NULL.
SELECT
CASE
WHEN status = 'paid' THEN 'completed'
WHEN status = 'refunded' THEN 'reversed'
ELSE 'other'
END AS status_group,
COUNT(*) AS order_count
FROM orders
GROUP BY
CASE
WHEN status = 'paid' THEN 'completed'
WHEN status = 'refunded' THEN 'reversed'
ELSE 'other'
END;The explicit ELSE is usually safer. It prevents unexpected values and missing statuses from silently becoming a NULL group. If status itself is NULL, neither comparison matches, so this query places that row in other.
Aliases and repeated expressions
Many SQL systems do not allow a SELECT alias in the same query block's GROUP BY clause. The portable approach is to repeat the expression. Repetition is verbose and can cause mismatches when the logic changes.
A subquery calculates the expression once:
SELECT
amount_band,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM (
SELECT
amount,
CASE
WHEN amount < 100 THEN 'small'
WHEN amount < 500 THEN 'medium'
ELSE 'large'
END AS amount_band
FROM orders
) AS classified_orders
GROUP BY amount_band
ORDER BY amount_band;This pattern also makes the intermediate result easier to test. First inspect the inner query to verify each row's classification. Then add the grouping query.
Grouping by expressions versus conditional aggregation
Grouping by an expression creates separate rows for each category. Conditional aggregation keeps one row and creates a column for each category.
SELECT
SUM(CASE WHEN amount < 100 THEN amount ELSE 0 END) AS small_total,
SUM(CASE WHEN amount >= 100 AND amount < 500 THEN amount ELSE 0 END) AS medium_total,
SUM(CASE WHEN amount >= 500 THEN amount ELSE 0 END) AS large_total
FROM orders;Choose grouped rows when the categories should be rows in a report. Choose conditional aggregation when a fixed set of categories should appear as columns.
Exercise
What group does an order with amount = 100 belong to in the amount-band example, and why?
Show answer
It belongs to the medium group. The condition amount < 100 is false, and the next condition amount < 500 is true.