SQL Kitchen

Lesson · Recipe № 011

Multiple JOINs

Lesson 11
Recipe

Multiple JOINs


A query isn't limited to two tables. Chain a second JOIN onto the first, and each new table can match against any table already in the query, not just the very first one.

Query

SELECT d.name, d.station, st.name AS lead
FROM dishes d
JOIN stations s ON d.station = s.name
JOIN staff st ON s.lead = st.name
ORDER BY d.name;

↓ result

d.name           d.station  lead
Baklava          pastry     Yannick
Bifteki          grill      Giorgos
Dakos            salad      Sofia
Loukoumades      pastry     Yannick
Melitzanosalata  salad      Sofia
Souvlaki         grill      Giorgos

Once a third table is in, you can filter on any column from any of them, exactly like a two-table join. Here the filter reaches all the way to staff, even though the question is about dishes.

Query

SELECT d.name, d.station
FROM dishes d
JOIN stations s ON d.station = s.name
JOIN staff st ON s.lead = st.name
WHERE st.years > 8
ORDER BY d.name;

↓ result

d.name    d.station
Bifteki   grill
Souvlaki  grill

The pattern doesn't change past three tables either: alias each table, join the next one to whichever table already has the matching column, and keep going.

On the rail · tonight's orders

ORDER 031

for Giorgos


New hires keep asking who to talk to about a dish. Giorgos wants a full rundown: every dish, its station, and who's leading that station tonight.

Your query returns

Each dish's name, its station, and the name of the person leading that station.


ORDER 032

for Eleni


Eleni wants to spotlight the dishes made by her most experienced hands: every dish cooked at a station led by someone with more than 5 years on the job.

Your query returns

Each dish's name and station, for stations led by someone with more than 5 years of experience.


ORDER 033

for Konstantinos


Konstantinos wants to settle an argument at the bar: which station leads are running the priciest sections, on average.

Your query returns

Each station lead's name and the average price of dishes at their station, priciest first.