Combine rows from two tables with JOIN ... ON, matching a column they share.
A song knows its artist's name. It does not know where the artist is from. That lives in a different table.
Real databases keep each kind of thing in its own table, so a fact is stored once. The music library now has two tables: songs and artists. The artist's name is in both. A JOIN lines up each song with its artist by matching that name.
Make your prediction first. Help opens once you've locked it in.
SELECT songs.title, artists.country
FROM songs
JOIN artists ON songs.artist = artists.name;
Open Tables in this database first to see both tables.
Run it and compare with your prediction.
| Part | What it does |
|---|---|
songs.title |
The title column of the songs table: table name, a dot, column name |
FROM songs JOIN artists |
Brings the two tables together |
ON songs.artist = artists.name |
Says which columns must match for a song and an artist to be paired |
SELECT songs.title, artists.country
FROM songs
JOIN artists ON songs.artist = artists.name;
SELECT songs.title, artists.country
FROM songs
JOIN artists ON songs.artist = artists.name
WHERE artists.country = 'Australia';
A join can be filtered with WHERE like any other query.
Say it aloud: a song and an artist go together when...
Run the query. How many songs are by artists from Australia?
Change the query so it shows each song's title and its artist's country.
Before a hint: what kind of stuck is this? Try a strategy first
Change artists.formed to the column you want.
The column is artists.country.
Show each song's title and its artist's country.
Run your program. This ticks when your code does all of the above.
Find out how many songs the library has from each country. Join the tables, then group.
Before a hint: what kind of stuck is this? Try a strategy first
Join, then GROUP BY the country.
SELECT artists.country, COUNT(*) FROM songs JOIN artists ON songs.artist = artists.name GROUP BY artists.country;
Count the songs from each country using JOIN and GROUP BY.
Run your program. This ticks when your code does all of the above.
Lesson done. You've finished every step you need.
Students combine two tables with JOIN ... ON and then filter or group the joined rows. About 30 minutes.
Open the teacher guide: answers, solutions, slides and a worksheet.
Picturing what the join does. Use two paper lists and draw lines between the matching rows.
Stretch: Show each song with the artist's formed year, newest bands first.
Support: Give the whole JOIN line and ask students to choose the columns.
Next lesson: change the data itself with INSERT, UPDATE and DELETE.