Ravindra BagaleCourses & study guides Track your progress

14. Why Tables Join: Keys and Relationships

14.2 One-to-Many: Customers and Shipments (What One Row Means)

Why. Before you join or total anything, you must know what one row stands for. Mistakes about this are the most common reason a report shows the wrong number.

What. The grain of a table is what one row means. In customers, one row is one customer. In shipments, one row is one shipment. One customer can have many shipments, so this is a one-to-many relationship. A customer can also have no shipments at all, like Marina Spices.

How. Count the shipments for each customer id inside the shipments table, without joining anything yet.

Steps

  1. Write one sentence for each table: one row in customers is one customer.
  2. Run the example and read the shipment count per customer.
  3. Notice that customer 206 does not appear, because it has no rows in shipments.
  4. Keep this in mind: a join with this table will repeat each customer once per shipment.

Examples

Example 1 · dataset: swiftship_logistics

SELECT customer_id,
       COUNT(*) AS shipments
FROM shipments
GROUP BY customer_id
ORDER BY customer_id;

Output

customer_idshipments
2012
2022
2032
2042
2052

Meaning. Each of the customers 201 to 205 has 2 shipments. Customer 206 is missing from this result, because a customer with no shipments has no rows here.

Ravindra Bagale's Tip

Write the grain as a comment at the top of your query, for example: one row = one shipment. It makes wrong totals much easier to spot.