SQLMentor // glossary

GROUP BY

GROUP BY collapses rows that share the same value in one or more columns into a single group, so aggregate functions like COUNT, SUM, and AVG can summarise each group separately.

Every column in the SELECT list that isn't wrapped in an aggregate function must appear in the GROUP BY list — the database needs to know what a single representative value for that column even means within a group.

Filter individual rows before grouping with WHERE; filter the resulting groups with HAVING, which runs after GROUP BY and can reference aggregate values.

Example

SELECT department_id, COUNT(*) AS emp_count, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;