Store another table's id in a column, so a row can point at exactly one row elsewhere.
A review says 'Great chorus'. Which song? The review stores a number, and the number points at one row.
The reviews table does not store song titles. It stores a song_id: the id of a row in songs. A column that holds another table's key is called a foreign key. A join matches it up: reviews.song_id = songs.id.
Why not just store the title? Titles can change or repeat. An id never does.
Make your prediction first. Help opens once you've locked it in.
SELECT songs.title, reviews.stars
FROM reviews
JOIN songs ON reviews.song_id = songs.id;
Run it. Open Tables in this database to see the song_id column.
| Part | What it does |
|---|---|
reviews.song_id |
The id of the song this review is about |
songs.id |
The primary key of the songs table |
ON reviews.song_id = songs.id |
Pairs each review with its song |
SELECT songs.title, reviews.stars
FROM reviews
JOIN songs ON reviews.song_id = songs.id;
SELECT songs.title, AVG(reviews.stars)
FROM reviews
JOIN songs ON reviews.song_id = songs.id
WHERE songs.title = 'Glass Hearts';
Join, filter to one song, average the stars.
What do the reviews actually store?
Run the query. What is the average rating of the song Glass Hearts?
Change the query so it shows each song title with the review's comment.
Before a hint: what kind of stuck is this? Try a strategy first
Swap reviews.stars for the column with the words.
The column is reviews.comment.
Show each review's comment beside its song title.
Run your program. This ticks when your code does all of the above.
Find the average rating of each reviewed song, with the best first.
Before a hint: what kind of stuck is this? Try a strategy first
Join, group by the song's title, and average the stars.
Add ORDER BY AVG(reviews.stars) DESC for best first.
Show each reviewed song with its average stars, best first.
Run your program. This ticks when your code does all of the above.
Lesson done. You've finished every step you need.
Students link two tables with a foreign key, join on it, and see why tables link by id rather than by name. About 30 minutes.
Open the teacher guide: answers, solutions, slides and a worksheet.
Seeing the link. Draw an arrow from each review row to its song row.
Stretch: Insert a review for a song, then run the join again to see it appear.
Support: Give the join and ask for the grouping.
Next: SQL from Python, which runs the same queries from a program.