GROUP BY

GROUP BY collapses rows that share the same value into a single group, so you can run an aggregate (like COUNT or SUM) on each group separately.

SQL

It is the key to questions like 'how many orders per customer?' or 'total sales per region?'. You group by the column you want one result row per, and apply an aggregate function to the rest.

To filter groups after grouping, use HAVING rather than WHERE, since WHERE filters individual rows before they are grouped.

Syntax

SELECT column, COUNT(*)
FROM table_name
GROUP BY column;

Examples

SQL

SELECT country, COUNT(*) AS users
FROM users
GROUP BY country;

Output:

country  users
-------  -----
USA      12
UK       7

Learn it in a lesson

See also

Back to the Dictionary