← Learning Hub
Beginner

GROUP BY and HAVING

GROUP BY splits rows into groups and runs the aggregate once per group. It answers questions like "How many products in each category?"

GROUP BY splits rows into groups and calculates an aggregate for each: revenue per city, orders per customer, products per category. It's how SQL answers "per" questions. HAVING then filters the groups, just like WHERE filters rows.

Example
SELECT category, COUNT(*) AS products, AVG(price) AS avg_price
FROM products
GROUP BY category;

-- Result:
-- category    | products | avg_price
-- ------------+----------+----------
-- Books       | 2        | 399
-- Electronics | 2        | 2749
-- Fashion     | 2        | 899
-- Home        | 2        | 624
-- Sports      | 1        | 799
▶ Try it yourself
Example
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;

-- Result:
-- status    | orders
-- ----------+-------
-- delivered | 3
-- shipped   | 2
-- placed    | 2
-- cancelled | 1
▶ Try it yourself

HAVING: filter the groups

WHERE filters rows before grouping. HAVING filters groups after grouping, using the aggregate.

Example
SELECT customer_id, COUNT(*) AS orders
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING COUNT(*) >= 2;

-- Result:
-- customer_id | orders
-- ------------+-------
-- 1           | 3
-- 2           | 2
▶ Try it yourself

The order SQL runs in

Writing order: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. SQL actually works it out as: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. That's why you can't use a SELECT alias inside WHERE.

Every column in the SELECT must either be in the GROUP BY or inside an aggregate. Most databases give an error otherwise.
Key points
  • GROUP BY makes one result row per group.
  • Every selected column must be grouped or aggregated.
  • WHERE filters rows before grouping; HAVING filters groups after.

📝 Test yourself

1. Which clause filters groups by an aggregate?
2. Which runs first?
3. Fill in the clause that makes one row per category:
SELECT category, COUNT(*) FROM products BY category;