Groups with GROUP BY

Stage 3: Aggregation · Lesson 11 of 17 · 6 min read · free, interactive

GROUP BY splits the rows into groups that share a value, and the aggregates are computed once per group:

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

NULL countries form a group of their own.

Every column in the SELECT list must either be in GROUP BY or be inside an aggregate. Otherwise the database wouldn't know which of the group's values to show.

SELECT category, COUNT(*) AS items, MIN(price) AS cheapest FROM items GROUP BY category;

You can group by several columns, and sort the result like any other query:

SELECT country, level, COUNT(*) AS players FROM players GROUP BY country, level ORDER BY country, level;

Practice

Each answer runs in your browser and is checked on hidden data.

Previous: Counting and totals · Next: Filtering groups with HAVING · All lessons