×

sql · level 2 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A join builds one wide table for the rest of the query.

The cafe keeps customers, dishes and orders in separate tables. Each order holds a customer_id, a dish_id and a quantity: how many of that dish were ordered.

FROM and JOIN work first and build a : every order paired with its customer. From then on, WHERE, GROUP BY and ORDER BY treat it like any other table.

So grouping by c.name gives one row per customer, and SUM(o.quantity) adds up the items each one ordered.

SELECT c.name, SUM(o.quantity) AS items
FROM orders o
JOIN customers c ON o.customer_id = c.id
GROUP BY c.name
ORDER BY items DESC, c.name;

Sam has not ordered anything yet, so Sam vanishes from this join. A later lesson brings Sam back.