NO. 09 · 7 exercises

9. Joins

The moment SQL starts earning its keep.

The lesson

Joins

Everything so far has been a one-table affair. But the store's data doesn't live in one table: the artists are in artists, their albums in albums, the songs in tracks. Ask "which songs belong to The Delta Kings?" without joins and you're stuck counting artist_ids by hand.

This is the chapter where SQL starts earning its keep. A join is how you ask a question across several tables at once — and it's the same one idea in every dialect, on every database, for the last forty years.

Look at tracks: there's no artist column. There's album_id, a number. Open albums and that number points to a row — which holds artist_id, pointing into artists. A column that stores the id of a row in another table is a foreign key, and foreign keys are the threads that stitch the database together.

Why numbers instead of names? Because names change ("The Delta Kings" becomes "The Delta Kings Revival" one day), but an id never does, and two rows can never share it.

Matching rows: the one idea

Here's the whole trick. Take two small tables:

idtitlealbum_id
1Golden Hour1
13Meridian Blue5
27Crossroads (Live)10
idtitle
1Golden Hour
5Meridian Blue
10Crossroads Live

A join walks every track, looks at its album_id, finds the album row whose id matches, and combines the two rows side by side into one:

title (track)title (album)
Golden HourGolden Hour
Meridian BlueMeridian Blue
Crossroads (Live)Crossroads Live

That's all a join is: for each row on the left, find the matching row on the right and glue them together. Everything below is a variation on that one sentence.

INNER JOIN: the default

SELECT t.title, a.title AS album
FROM tracks t
JOIN albums a ON t.album_id = a.id;

Read it out loud: tracks joined with albums, where a track's album_id equals an album's id. All 49 tracks come back, each carrying its album's title.

Two habits to start now:

  • Aliases. tracks t is short for tracks AS t. Both tables have a title column, so t.title and a.title are the only way to tell them apart. With one table you can skip aliases; with joins they're not optional.
  • ON describes the matching rule. The comparison t.album_id = a.id is the whole contract of the join.

JOIN means INNER JOIN: rows are kept only when a match exists. Every track has an album here, so nothing is lost — 49 tracks stay 49 rows. If a track ever pointed at a missing album, its row would simply vanish.

Three tables, one answer

tracks → albums → artists: each hop is the same move.

SELECT t.title, a.title AS album, ar.name AS artist
FROM tracks t
JOIN albums a ON t.album_id = a.id
JOIN artists ar ON a.artist_id = ar.id;

The second join doesn't care that it's following a chain — it just matches albums.artist_id to artists.id. Joins are flat, not nested: you can line up four of them in a row, and it's still one pass over the tables.

LEFT JOIN: keep the unmatched

An INNER join drops rows that find no partner. Sometimes the rows with no partner are the answer.

The staff: every customer has a support_rep_id, but only employees 3, 4 and 5 actually carry customers. Sofia Duarte and Ken Ito support no one — and Jane Foster and Tom Reyes are management. Who has no customers at all? With LEFT JOIN, all seven employees survive the join, and the customer columns fill with NULL where there was no match:

SELECT e.first_name, e.last_name
FROM employees e
LEFT JOIN customers c ON e.id = c.support_rep_id
WHERE c.id IS NULL;

Four names come back: Jane Foster, Tom Reyes, Sofia Duarte and Ken Ito. The rule: start from the left table's rows; attach a match when one exists, otherwise leave NULL. Forget Venn diagrams — picture the left table's rows laid out first, then each one either receiving its match or not.

That WHERE c.id IS NULL is the standard "find the non-matches" idiom: the customer id is the thing that should have matched, so NULL there means "no match".

A table joined with itself

Every employee except Jane Foster has a reports_to — the id of their manager, who is also a row in employees. Joining a table to itself is legal and common; the only trick is giving the table two aliases:

SELECT e.first_name || ' ' || e.last_name AS employee,
       m.first_name || ' ' || m.last_name AS manager
FROM employees e
LEFT JOIN employees m ON e.reports_to = m.id;

Read the chain from the bottom: Tom Reyes reports to Jane Foster, Ana Beltrán and Marcus Webb and Priya Nair report to Tom Reyes... and Jane's reports_to is NULL, so the LEFT JOIN leaves her manager's name as NULL. One query, the whole org chart.

USING vs ON

When the two joining columns have the same name, SQLite lets you write USING (column) instead of ON:

SELECT e.first_name, c.first_name AS customer
FROM employees e JOIN customers c USING (support_rep_id);

That works here — both sides are called support_rep_id. But our track–album join can't use it: the columns are tracks.album_id and albums.id, different names. That's why ON is the general tool: it works for any two columns, whatever they're called. Think of USING as a courtesy for when the schema already agrees.

Joins + aggregates: revenue by artist

Now the famous one. invoice_lines records every sale. Follow the chain all the way to the artist and add up the money:

SELECT ar.name,
       ROUND(SUM(il.quantity * il.unit_price), 2) AS revenue
FROM invoice_lines il
JOIN tracks t ON il.track_id = t.id
JOIN albums a ON t.album_id = a.id
JOIN artists ar ON a.artist_id = ar.id
GROUP BY ar.name;

Ten artists appear — and notice what doesn't: The Delta Kings and Iron Bloom sold nothing, and inner joins removed them. Sometimes that's exactly what you want... and sometimes you want the zeros to show. That's where LEFT JOIN plus a COALESCE from chapter 8 comes in:

SELECT ar.name, COALESCE(SUM(il.quantity * il.unit_price), 0) AS revenue
FROM artists ar
LEFT JOIN albums a ON ar.id = a.artist_id
LEFT JOIN tracks t ON a.id = t.album_id
LEFT JOIN invoice_lines il ON t.id = il.track_id
GROUP BY ar.name;

Start from artists (all twelve), attach whatever matches, and COALESCE turns the empty artists' NULL totals into 0. Grouping, conditional logic and joins in one query — that's the boss recipe.

Joins + dates: the monthly books

Dates join just like anything else. The accountants want revenue per month — a GROUP BY over a strftime expression from chapter 7:

SELECT strftime('%Y-%m', i.invoice_date) AS month,
       ROUND(SUM(il.quantity * il.unit_price), 2) AS revenue
FROM invoices i
JOIN invoice_lines il ON i.id = il.invoice_id
GROUP BY strftime('%Y-%m', i.invoice_date);

Twenty months of the store's life, each with one number. Add ORDER BY ... DESC and LIMIT from chapter 4 and you have the newest ten on demand.

What you just learned

  • A join combines rows from two tables where the ON condition is true; JOIN is INNER JOIN, which keeps only matches.
  • Foreign keys (album_id, artist_id, support_rep_id, reports_to) are the threads; aliases (tracks t) keep columns apart.
  • LEFT JOIN keeps every left-table row, filling unmatched columns with NULL; WHERE right_table.id IS NULL finds non-matches.
  • Self-joins use two aliases of the same table; chains of joins can reach across five tables.
  • Joins compose with everything before: aggregates, GROUP BY, COALESCE, date functions, ORDER BY, LIMIT.

Dialect note. INNER JOIN and LEFT JOIN work identically in PostgreSQL, MySQL and SQL Server. SQLite is the odd one out in one way: it has no RIGHT JOIN or FULL OUTER JOIN. You don't need them often — a right join is just a left join with the tables swapped — and a full outer join can be faked with LEFT JOIN plus UNION, which you'll meet properly in chapter 11.

The last exercise of this chapter puts five tables on the table at once. If you can write it, you can query any record store that ever existed.