The GROUP BY
clause is used to group rows that have the same value in one or more columns. It’s commonly used with aggregate functions like COUNT
, SUM
, or AVG
to get summary data for each group.
To group students by age and count how many students are in each group:
SELECT age, COUNT(*) FROM students GROUP BY age;
This returns one row per age, showing how many students have that age.
While WHERE
filters individual rows before grouping, the HAVING
clause filters groups after aggregation. For example:
SELECT age, COUNT() FROM students GROUP BY age HAVING COUNT() > 1;
This shows only ages that appear more than once in the table.