Students link two tables with a foreign key, join on it, and see why tables link by id rather than by name.
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.
Predict and Run 8 min · Investigate 8 min · Modify and Make 14 min
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.
Print the ten reviews and the songs table. Students draw an arrow from each review to its song using song_id, then run the join to check.
Seeing the link. Draw an arrow from each review row to its song row.
| What you will see | A question to ask | The fix |
|---|---|---|
| ambiguous column name: id | Both tables have an id. Which one do you mean? | Write songs.id or reviews.id. |
| Fewer rows than expected. | Which songs have no reviews? | A join keeps only rows that have a match. |
One possible solution for each task. Other correct programs are fine.
SELECT songs.title, reviews.comment
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
GROUP BY songs.title
ORDER BY AVG(reviews.stars) DESC;
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.
Why does reviews store song_id instead of the song's title?
An id is never repeated or changed, so each review points at exactly one song and a title can be fixed in one place.
Next: SQL from Python, which runs the same queries from a program.