← Teacher guide

One answer for each group

Students use GROUP BY to get a summary for each value of a column, and sort the groups.

SQL and databases · Summarise · about 30 minutes · Open the student lesson

Classroom resources

Open these in Waypoints Prepare with one click. To share a file another way, copy its address and paste it into Load URL, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.

Students will be able to

Timing

Predict and Run 8 min · Investigate 8 min · Modify and Make 14 min

Running the lesson

  1. Predict: draw five piles on the board and sort a few song cards into them before anyone runs it.
  2. Run: the counts add to 15, which shows no song is lost or counted twice.
  3. Make: ORDER BY can use the summary, as in ORDER BY COUNT(*) DESC.

In class

On the slides at these points. Students can do the whole lesson on their own; these are for the room. In the deck, the Run, Modify and Make slides have the live playground in them (the tutorial link is the backup), and the notes above are in each slide's speaker notes.

The hard part (on purpose)

Seeing why the count is for a pile, not the table. Sort cards into piles by hand first.

When students get stuck

What you will seeA question to askThe fix
Only one row, with an odd genre.Is there a GROUP BY?Add GROUP BY and the column you want a row for.
GROUP BY comes before WHERE and gives an error.What is the order of the parts?SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT.

Answers to the checks

  1. Predict: There are five different genres. What will this show?
    5 rows. The songs are put in a pile for each genre, and COUNT(*) counts each pile.
  2. Count the piles: Run the query. How many different artists are in the table?
    5
  3. Total for each artist: You want the total plays for each artist. Which query?
    SELECT artist, SUM(plays) FROM songs GROUP BY artist;
    Show the artist, add up the plays, and group by the artist.

Solutions

One possible solution for each task. Other correct programs are fine.

Modify

SELECT genre, SUM(plays)
FROM songs
GROUP BY genre;

Make

SELECT artist, COUNT(*)
FROM songs
GROUP BY artist
ORDER BY COUNT(*) DESC
LIMIT 1;

Stretch and support

Stretch: Add WHERE year >= 2020 and see how the counts change.

Support: Give the query with GROUP BY filled in and ask for the summary.

Exit ticket

What does GROUP BY genre do?

It makes one pile for each genre, so a summary such as COUNT(*) gives one answer for each genre.

What each step is for

Where it leads

Next lesson: a second table, and joining the two.