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.
- Write the query: For each item
category, return how many items it has asitems. Row order does not matter. - Fill in the blanks: For each country, return the average
levelrounded to 1 decimal asavg_level. Skip players with no country. Row order does not matter. - Find the bug: Return each
categorywith the price of its most expensive item astop_price. Row order does not matter.
Previous: Counting and totals · Next: Filtering groups with HAVING · All lessons