SQL GROUP BY & Aggregate Functions
Learn to summarise and group data โ the foundation of business reporting and one of the most tested SQL skills in every analyst interview.
Aggregate Functions
Aggregate functions collapse multiple rows into a single summary value. They are the most used SQL functions in business analytics โ every dashboard, every report, every KPI uses aggregates.
| Function | What it returns | NULL behaviour |
|---|---|---|
COUNT(*) | Total rows including NULLs | Counts everything |
COUNT(col) | Non-NULL values in column | Ignores NULLs |
COUNT(DISTINCT col) | Unique non-NULL values | Ignores NULLs & duplicates |
SUM(col) | Total of all values | Ignores NULLs |
AVG(col) | Mean of all values | Ignores NULLs (not zero!) |
MIN(col) | Smallest value / earliest date | Ignores NULLs |
MAX(col) | Largest value / latest date | Ignores NULLs |
GROUP BY โ Aggregate Per Group
GROUP BY divides rows into groups and applies aggregate functions to each group separately. This answers “total revenue PER region” or “orders PER customer” โ the most common analytics questions.
HAVING โ Filter After Grouping
HAVING filters groups after GROUP BY runs. It’s like WHERE but for groups. This is a very common interview topic โ knowing when to use WHERE vs HAVING sets you apart.
WHERE vs HAVING: WHERE filters individual rows BEFORE grouping. HAVING filters groups AFTER grouping. Use WHERE to filter raw data. Use HAVING to filter the result of aggregations.
CASE WHEN โ Conditional Logic in SQL
Practice Questions โ GROUP BY
COUNT(*) AS orders,
SUM(order_amount) AS revenue
FROM orders
GROUP BY category
ORDER BY revenue DESC;
FROM orders
GROUP BY category
HAVING AVG(order_amount) > 8000
ORDER BY avg_order DESC;
COUNT(CASE WHEN status=‘delivered’ THEN 1 END) delivered_orders,
COUNT(CASE WHEN status=‘returned’ THEN 1 END) returned_orders,
SUM(CASE WHEN status=‘delivered’ THEN order_amount ELSE 0 END) revenue
FROM orders GROUP BY region;
Ready to practice GROUP BY with a mentor?
Book a free SQL mock session. We’ll run real groupby interview questions and give live feedback.
Book Free Session