Skip to content
CodeItRaw
SQL: Grouping

Lesson 1/2

So far every query brought rows as they are. Aggregate functions reduce many rows to one number: COUNT(*) the number of rows, SUM the total, AVG the average, MIN and MAX the smallest and largest.

SELECT genre, COUNT(*) AS books
FROM books
GROUP BY genre;
GROUP BY sorts the rows into heaps of those sharing a genre; the aggregate function runs separately for each heap. The result has one row per genre. AS names the result column.

Without GROUP BY an aggregate function treats the whole table as one heap and returns one row: SELECT COUNT(*) FROM books is the number of books. Mind what you count: COUNT(*) counts rows, COUNT(translator) only the rows where the translator is not missing.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    How many?

    SQL query

  2. 02

    Per department

    SQL query

If you would rather not wait for the order, every problem is open without locks: Problem list