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
- Run the first example and copy the ten shipments onto paper.
- Run the second example and write the five hubs next to them.
- Draw a line from each shipment to its hub; you should draw 8 lines.
- 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_id | customer_id | hub_id |
|---|---|---|
| 1001 | 201 | 1 |
| 1002 | 201 | 1 |
| 1003 | 202 | 2 |
| 1004 | 203 | 3 |
| 1005 | 203 | 3 |
| 1006 | 204 | 4 |
| 1007 | 205 | 1 |
| 1008 | 202 | 2 |
| 1009 | 204 | 9 |
| 1010 | 205 | NULL |
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_id | hub_code | city |
|---|---|---|
| 1 | PNQ-01 | Pune |
| 2 | BOM-02 | Mumbai |
| 3 | DXB-01 | Dubai |
| 4 | LHR-03 | London |
| 5 | SIN-01 | Singapore |
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.
Ravindra Bagale's Tip – मराठी
Join चालवण्याआधी अपेक्षित rows चा आकडा लिहून ठेवा. SQL वेगळा आकडा देत असेल तर result वापरण्याआधी त्याचं कारण शोधा.
Ravindra Bagale's Tip – हिंदी
Join चलाने से पहले अपेक्षित rows की गिनती लिख लीजिए। SQL अलग संख्या दे तो result इस्तेमाल करने से पहले कारण ढूँढिए।