Use GROUP BY to count or add up for each genre, artist or year at once.
How many songs in each genre? You could run five queries, or ask once.
COUNT(*) gave one answer for the whole table. GROUP BY sorts the rows into piles, one pile for each value in a column, and gives one answer for each pile.
How this lesson works: Predict, Run, Investigate, Modify, Make
Predict: Read the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.
Run: Run it and compare the result with your prediction.
Investigate: Trace how each line of code connects to what you see.
Modify: Change the code on purpose and check the result.
Make: Build something new using what you have learned. Expect a few tries; that is normal.
Make your prediction first. Help opens once you've locked it in.
PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.
Predict
lesson.sql
SELECT genre, COUNT(*)
FROM songs
GROUP BY genre;
RunRun it and compare the result with your prediction.
Run
Run it and add up the counts in your head. They should come to 15.
Part
What it does
SELECT genre, COUNT(*)
Shows the group's name and its count
GROUP BY genre
Makes one pile for each genre
lesson.sql
SELECT genre, COUNT(*)
FROM songs
GROUP BY genre;
Try it yourselfYour edits are saved in this browser.
InvestigateTrace how each line of code connects to what you see.
Investigate
lesson.sql
SELECT artist, AVG(seconds)
FROM songs
GROUP BY artist;
One row for each pile.
Group by the column you want a row for.
Run the query. How many different artists are in the table?
ModifyChange the code on purpose and check the result.
Modify
Change the query so it shows the total plays for each genre.
Try it yourselfYour edits are saved in this browser.