Skip to content

Group and aggregate

Collapse many rows into one row per group, and know exactly what one row of the result stands for.

Practise: 26 questions

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

Variations

In other warehouses

Practise group and aggregate