The GROUP BY Clause
The GROUP BY clause groups rows that have the same values so you can calculate aggregate statistics for each group.
💡 GROUP BY is the foundation of data aggregation in SQL.
Basic Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
;
Example
SELECT department, COUNT(*) AS employee_count, ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;
WHERE vs HAVING
| Clause | Filters | When | Can Use Aggregates |
|---|---|---|---|
| WHERE | Individual rows | Before GROUP BY | No |
| HAVING | Groups | After GROUP BY | Yes |
✏️ Exercise: Write a query that uses GROUP BY to count employees per department
See Solution
SELECT department, COUNT(*) AS count
FROM employees
GROUP BY department
ORDER BY count DESC;
✅ Key Takeaways
- GROUP BY groups rows for aggregate calculations
- Use with aggregate functions like COUNT, SUM, AVG, MIN, MAX
- WHERE filters individual rows BEFORE grouping
- HAVING filters groups AFTER grouping
- ORDER BY comes last after GROUP BY and HAVING