Sub topic 9
Grouping by expressions such as CASE
This chapter assumes you can write a basic GROUP BY query, know that every non-aggregated column in the SELECT list must be grouped, and know the logical order in which a query is evaluated. The examples use the orders table from earlier chapters: order_id, customer_id, amount, status and shipped_at. Some examples also use an order_date column.
Grouping by a computed value
GROUP BY does not have to name a column. It accepts any expression, and rows that produce the same value for that expression land in the same group. This lets you group by something the table does not store, such as a size band, a year, or a yes/no flag.
The most common tool is a CASE expression. It turns a continuous or messy column into a small set of labels.
SELECT CASE
WHEN amount IS NULL THEN 'unknown'
WHEN amount < 50 THEN 'small'
WHEN amount < 200 THEN 'medium'
ELSE 'large'
END AS size_band,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY CASE
WHEN amount IS NULL THEN 'unknown'
WHEN amount < 50 THEN 'small'
WHEN amount < 200 THEN 'medium'
ELSE 'large'
END
ORDER BY MIN(amount);The database evaluates the CASE once per row, then groups on the resulting label. Each distinct label becomes one output row, and the aggregates are computed within that label.
Two details in this query matter:
- The expression appears twice, once in
SELECTand once inGROUP BY. The two copies must match exactly. If they differ, the database sees theSELECTexpression as ungrouped. ORDER BY MIN(amount)sorts the bands from smallest to largest. Sorting bysize_bandwould give alphabetical order: large, medium, small, unknown. BecauseORDER BYruns after grouping, it can use an aggregate.
Why the alias often does not work in GROUP BY
Evaluation order explains a common error. In standard SQL, FROM and WHERE run first, then GROUP BY, then HAVING, then SELECT, then ORDER BY. The alias size_band is created in the SELECT step. When GROUP BY runs, that alias does not exist yet.
Some databases relax this rule as a convenience. Others follow the standard strictly.
| Database | Alias allowed in GROUP BY? |
|---|---|
| PostgreSQL | Yes |
| MySQL | Yes |
| SQLite | Yes |
| SQL Server | No |
| Oracle | Not in older versions |
A query that uses the alias works on PostgreSQL and fails on SQL Server. If your code must run on more than one database, do not rely on the alias.
You have three portable options:
- Repeat the full expression in
GROUP BY, as in the first example. - Compute the expression in a subquery or common table expression (CTE), then group by the resulting column.
- Group by position, for example
GROUP BY 1.
Option 3 is allowed by many databases, but it breaks silently when someone reorders the SELECT list. Avoid it in code that other people will maintain.
Computing the expression once with a CTE
Repeating a long CASE invites typos and drift. A CTE computes it once, and the outer query groups by an ordinary column.
WITH banded AS (
SELECT order_id,
amount,
CASE
WHEN amount IS NULL THEN 'unknown'
WHEN amount < 50 THEN 'small'
WHEN amount < 200 THEN 'medium'
ELSE 'large'
END AS size_band
FROM orders
)
SELECT size_band,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM banded
GROUP BY size_band
ORDER BY MIN(amount);This version works on every major database. Changing a threshold now means editing one place. It also lets you reuse size_band in several queries by turning the CTE into a view.
Other useful expressions
Any expression that returns one value per row can be a grouping key.
Grouping by calendar year, assuming orders has an order_date column:
SELECT EXTRACT(YEAR FROM order_date) AS order_year,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY EXTRACT(YEAR FROM order_date)
ORDER BY order_year;EXTRACT is standard SQL and works in PostgreSQL, MySQL and Oracle. SQL Server uses YEAR(order_date) instead. Some databases offer shortcuts such as DATE_TRUNC('month', order_date) in PostgreSQL, which truncates a date to the start of its month and so groups by month.
Grouping by a numeric bucket works the same way. For example, FLOOR(amount / 100) * 100 groups amounts into hundreds. Be careful with integer division. If amount is an integer column, some databases truncate amount / 100 before FLOOR sees it. That is harmless for positive values, but check how your database handles negative numbers and mixed types.
Grouping by a boolean flag is a compact way to compare two populations:
SELECT shipped_at IS NOT NULL AS is_shipped,
COUNT(*) AS order_count
FROM orders
GROUP BY shipped_at IS NOT NULL;This form works in PostgreSQL, MySQL and SQLite. SQL Server has no boolean type for this, so use CASE WHEN shipped_at IS NULL THEN 'pending' ELSE 'shipped' END there.
How NULL behaves inside grouping expressions
Grouping puts all NULL keys into one group, even though NULL is not equal to anything. A CASE expression adds two traps on top of that.
No ELSE means NULL. If no WHEN branch matches and you omit ELSE, the result is NULL. Those rows form a NULL group, which usually looks like a bug in the output. Add an explicit ELSE so every row gets a label you chose.
NULL falls through comparisons. The test amount < 50 is unknown when amount is NULL. A CASE treats an unknown test as not matching, so the row moves to the next branch and eventually reaches ELSE. In the first example, a missing amount would be labeled 'large' if the IS NULL branch were removed. That is a quiet mistake, because the output looks plausible.
Branch order matters. A CASE returns the first matching branch. If you write WHEN amount < 200 before WHEN amount < 50, the small band never receives any rows. List ranges from narrowest to widest, or give each branch both bounds.
The select list rule still applies
The select list rule from earlier chapters applies to expressions as well. Every item in SELECT must be an aggregate, a grouping expression, or something computed only from those.
Suppose you group by the size_band expression and also select amount. Most databases reject this, because many different amounts share one band and the database cannot choose one. MySQL with ONLY_FULL_GROUP_BY disabled may accept it and return an arbitrary amount, which is worse.
The reverse is fine. You may select an expression built from grouping keys. If you group by EXTRACT(YEAR FROM order_date), selecting EXTRACT(YEAR FROM order_date) + 1 is allowed, because it depends only on the grouping key.
Be careful with expressions that look alike but are not identical. Grouping by UPPER(status) and selecting status is an error. The database groups on the uppercase value, and several raw status values can map to one group.
Expressions in GROUP BY versus conditional aggregation
Both techniques use CASE, but they produce different shapes.
| Technique | Where CASE goes | Result shape |
|---|---|---|
| Group by expression | Inside GROUP BY | One row per label |
| Conditional aggregation | Inside an aggregate such as SUM | One column per label |
Grouping by expression returns a tall result, one row per band. Conditional aggregation returns a wide result, one column per category, which suits pivot-style reports. Use the tall form when the number of categories is open-ended or may change. Use the wide form when the categories are fixed and the reader expects them as columns.
Performance notes
A grouping expression is computed for every row that survives WHERE. A plain column can sometimes use an index to produce groups in order. An expression such as EXTRACT(YEAR FROM order_date) usually cannot use an ordinary index on order_date, so the database sorts or hashes the computed values. On large tables, filter with WHERE first to shrink the input. Some databases let you create an index on the expression itself. That is a tuning step to take only after you measure a slow query.
Avoid non-deterministic expressions such as RANDOM() as grouping keys. The database may evaluate the expression separately in SELECT and GROUP BY, giving mismatched values or an error.
Summary of the working rules
- Any expression that returns one value per row can be a grouping key.
- Write the same expression in
SELECTandGROUP BY, or compute it once in a CTE or subquery. - Do not depend on aliases in
GROUP BYif the query must be portable. - Cover
NULLwith an explicitCASEbranch and provide anELSE. - Order the branches carefully, because the first match wins.
- Sort labelled bands with an aggregate such as
MIN(amount), not by the label text.
Exercise
A query groups orders with GROUP BY CASE WHEN amount < 100 THEN 'low' WHEN amount < 500 THEN 'mid' END. Some rows come back under a group whose label is NULL. Name two kinds of rows that can land there, and show how to fix the CASE so that each gets a clear label.
Show answer
Rows with amount of 500 or more match no branch, and with no ELSE the result is NULL. Rows where amount is NULL also match no branch, because the comparisons are unknown. Fix it with an explicit NULL branch and an ELSE: CASE WHEN amount IS NULL THEN 'unknown' WHEN amount < 100 THEN 'low' WHEN amount < 500 THEN 'mid' ELSE 'high' END. Use the same expression in SELECT and GROUP BY, or compute it in a CTE.
Exercise
Your query selects EXTRACT(YEAR FROM orderdate) AS orderyear and groups by order_year. It runs on PostgreSQL but fails on SQL Server. Why, and what are two portable rewrites?
Show answer
GROUP BY runs before SELECT in the logical order, so the alias orderyear does not exist yet. PostgreSQL allows the alias as an extension, and SQL Server does not. One rewrite repeats the expression in GROUP BY (use YEAR(orderdate) on SQL Server). The other computes the year in a CTE or subquery and groups by that column in the outer query.