← SQL and databases

One summary per group

COUNT, SUM or AVG for each category.

Start this lesson

COUNT(*) on the whole table gives one number. Often you want one number per group: books per genre, members per city. GROUP BY column puts rows with the same value into a group, and each aggregate is computed for each group separately. The result has one row per group.

SELECT genre, COUNT(*) AS books
FROM books
GROUP BY genre;

Five genres, so five rows: each genre with how many books it has.

Rule of thumb: every column in the SELECT should either be in the GROUP BY or be inside an aggregate. SELECT genre, title, COUNT(*) … GROUP BY genre is unclear, because a group has many titles. SQLite quietly picks one; other databases give an error.