Ravindra BagaleCourses & study guides Track your progress

14. Why Tables Join: Keys and Relationships

14.4 Practice: Match Shipments to Hubs on Paper First

Why. Matching a few rows by hand first shows you exactly what a join should return. Then you can trust or question the SQL result.

What. On paper, you take each shipment, read its hub_id, and look for the same hub_id in hubs. You note three outcomes: one match, no match because the hub does not exist, and no match because the hub is missing.

How. List shipments with their hub_id, list hubs, and match them yourself before you run any join.

Steps

  1. Run the first example and copy the ten shipments onto paper.
  2. Run the second example and write the five hubs next to them.
  3. Draw a line from each shipment to its hub; you should draw 8 lines.
  4. Mark 1009 as hub not found and 1010 as hub missing, and see that hub 5 Singapore gets no line.

Examples

Example 1 · dataset: swiftship_logistics

SELECT shipment_id, customer_id, hub_id
FROM shipments
ORDER BY shipment_id;

Output

shipment_idcustomer_idhub_id
10012011
10022011
10032022
10042033
10052033
10062044
10072051
10082022
10092049
1010205NULL

Meaning. Ten shipments. Eight have a hub_id that exists in hubs, 1009 has 9, and 1010 has NULL.

Example 2 · dataset: swiftship_logistics

SELECT hub_id, hub_code, city
FROM hubs
ORDER BY hub_id;

Output

hub_idhub_codecity
1PNQ-01Pune
2BOM-02Mumbai
3DXB-01Dubai
4LHR-03London
5SIN-01Singapore

Meaning. Five hubs. Singapore (hub 5) has no shipments yet, so no line reaches it.

Ravindra Bagale's Tip

Write down your expected row count before you run a join. If SQL returns a different number, find out why before you use the result.