When you need it
Any question that says "per", "by", "each", "total", "average" or "how many" is asking for a group and an aggregate. Revenue per category, orders per customer, tickets per agent. The prompt also tells you the grain of the result: one row per what?
Say the grain out loud before you write anything. "One row per category" decides your GROUP BY. If you cannot say it, you are not ready to write the query.
The shape of the query
select <group columns>, <aggregates>
from <tables>
where <row filter>
group by <group columns>
having <group filter>
order by <sort>;Read it in the order the database runs it. FROM and joins build the rows. WHERE removes rows. GROUP BY folds the rest into groups. HAVING removes whole groups. SELECT computes the output. ORDER BY sorts.
Every column in SELECT must be either in GROUP BY or inside an aggregate. That is the rule that catches most syntax errors.
select category,
count(*) as products,
round(avg(list_price), 2) as avg_price,
min(list_price) as cheapest
from products
group by category
order by category;The next one filters twice. WHERE limits the rows going in (completed orders only). HAVING limits the groups coming out (at least five orders).
select channel,
count(*) as orders,
sum(shipping_fee) as shipping_collected
from orders
where status = 'completed'
group by channel
having count(*) >= 5
order by orders desc, channel;Traps interviewers look for
WHEREversusHAVING. A condition on a raw column goes inWHERE. A condition on an aggregate (count(*) > 5) can only go inHAVING. Putting a row filter inHAVINGworks but is slower and signals you do not know the order of evaluation.COUNT(*)versusCOUNT(column).COUNT(*)counts rows.COUNT(column)skips NULLs.COUNT(DISTINCT column)skips NULLs and repeats. Pick the one that matches the question, such as distinct customers, not rows.- Groups that do not exist.
GROUP BYonly returns groups that have rows. If a category had no sales, it vanishes. To keep it, start from the table that lists all categories andLEFT JOINthe facts to it, then put the date or status filter in theONclause, not inWHERE. - Fan-out before the aggregate. Joining orders to order items and then summing an order-level column such as
shipping_feecounts the fee once per item. Aggregate each table to the grain you need first, then join. - Average of averages. The average of group averages is not the overall average unless the groups are the same size. Sum and count, then divide.
- Ungrouped NULLs. All NULLs in a grouping column land in one group. That is usually what you want, but label it with
COALESCE(col, 'unknown')so the reader can tell.
Variations
- Distinct counts. "How many customers ordered" is
count(distinct customer_id), notcount(*). - Several aggregates in one pass. Totals, counts and averages can share one
GROUP BY. Do not run the query three times. - Group by an expression. You can group by a computed value such as
date_trunc('month', ordered_at). Most engines also let you group by the select position (group by 1), which is fine for scratch work and risky in a long query. - Whole table as one group. With no
GROUP BY, aggregates return exactly one row, even on an empty table (COUNTgives 0,SUMgives NULL). - Top groups. Aggregate first, then
ORDER BY ... LIMIT. See the ranking lesson when you need ties handled.
In other warehouses
- Snowflake and BigQuery allow
GROUP BY ALLto group by every non-aggregate column in the select list. Handy, but spell out the columns in an interview unless asked. - SQL Server does not allow a select alias in
GROUP BYorHAVING. PostgreSQL allows the alias inGROUP BYbut not inHAVING. When in doubt, repeat the expression. - BigQuery has
COUNTIF(condition)andSUM(IF(...)). SQL Server needsSUM(CASE WHEN ... THEN 1 ELSE 0 END). - SQL Server uses
TOP ninstead ofLIMIT n.