5 min read
•Question 6 of 29mediumHow does GROUP BY work?
Aggregating data in SQL.
What You'll Learn
- GROUP BY basics
- Aggregate functions
- HAVING clause
Basic GROUP BY
query.sqlSQL
-- Count users per country
SELECT country, COUNT(*) as user_count
FROM users
GROUP BY country;
-- Result:
-- | country | user_count |
-- |---------|------------|
-- | USA | 150 |
-- | UK | 75 |
-- | Canada | 50 |Aggregate Functions
query.sqlSQL
SELECT
category,
COUNT(*) as total_products,
SUM(price) as total_value,
AVG(price) as avg_price,
MIN(price) as min_price,
MAX(price) as max_price
FROM products
GROUP BY category;GROUP BY Multiple Columns
query.sqlSQL
SELECT
country,
city,
COUNT(*) as user_count
FROM users
GROUP BY country, city
ORDER BY country, user_count DESC;HAVING Clause
Filter groups (WHERE filters rows, HAVING filters groups).
query.sqlSQL
-- Countries with more than 100 users
SELECT country, COUNT(*) as user_count
FROM users
GROUP BY country
HAVING COUNT(*) > 100;
-- Categories with average price > $50
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category
HAVING AVG(price) > 50
ORDER BY avg_price DESC;WHERE vs HAVING
query.sqlSQL
SELECT category, AVG(price) as avg_price
FROM products
WHERE status = 'active' -- Filters rows BEFORE grouping
GROUP BY category
HAVING AVG(price) > 50 -- Filters groups AFTER grouping
ORDER BY avg_price DESC;