Module 4 · Relating tables

Practice: choose and check a JOIN

By the end you will be able to choose the JOIN and count matches, including zero.

About 25 min

0 of 52 lessons

Before you start, you need

Combine tables and keep control of the result rows

The problem

You will count shipped orders per customer and books per author. The lists must also include anyone with zero. First decide which table must keep all its rows.

To keep customers, put them on the left of a LEFT JOIN. The shipped-orders condition must limit the matches in ON. Then gather the rows for each customer with GROUP BY.

Count the id from the right-hand table. COUNT(p.id) counts real orders. COUNT(*) would also count the kept row of a customer with no orders and show 1 instead of 0.

Check a case with no matches, one with a single match and one with several. In the challenge the tables will change, but you will still need to keep the missing ones and count the right matches.

How to think about it

What does COUNT(*) count on the row of a customer with no matches?

  • Keep customers and limit the matches to shipped orders inside ON.
  • Group by id and name. Count p.id, because it is missing when there is no matching order.
  • Check a customer with zero, one and several shipped orders. In the challenge, apply that same decision to authors and books.

Guided practice

Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.

Guided practice

Count shipped orders, including zero

Not started

Write a query that returns every customer and the number of shipped orders each one has, including zero.

Expected result: 12 rows with the columns name, shipped, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Challenge

Solve this variation. Spot the part that has changed before you look for help.

Practice

Count books per author

Not started

Show the author's name and COUNT(l.id) as books for every author, including those with no books.

Expected result: 6 rows with the columns name, books, in that order. Row order does not matter.

This activity uses a copy of the data with extra edge cases. Open the full data before you predict the result.

View tables and data

Open this panel to see the full data.

Key takeaways

  • First choose which rows should be kept.
  • Count the right-hand key to get zero when there are no matches.
  • Group by the entity's id.

Next: Answer questions with subqueries