Why Combine data at all?
Warehouses keep data in many small related tables. A single 5-billion-row table with every column repeated costs millions of dollars a month in storage.
So we store once, and combine only when we report or analyse.
Two directions JOIN vs UNION
UNION needs the same structure: same number of columns, same order, compatible data types. JOIN needs a matching key.
Data model Fact, dimension, keys
- Fact table: transactions or events. Large, updated all the time (
Sales_orders,Sales_orders_detail). - Dimension table: descriptive context. Small, rarely changes (
Dim_Product,Dim_Territory). - Primary key (PK): unique, never NULL. Foreign key (FK): points to a PK in another table.
Process Four steps before every JOIN
- Expected output first. Pick the starting (LEFT) table: the one whose rows you must keep, usually the fact table or the more detailed one.
- List the extra info you need and which table holds it.
- Find the keys that connect the tables. Check their data types match.
- Run, then validate: row count, NULLs, duplicates.
JOIN types What each one keeps
Stack rows UNION vs UNION ALL
UNION removes duplicate rows. UNION ALL keeps everything and is faster.
In class: orders of the 2011 and 2012 top-10 customers gave 160 rows with UNION and 180 with UNION ALL. Two customers are in both lists.
Use for combining final results, e.g. a "Shortest" and a "Longest" list with a label column.
Watch out Mistakes seen in this lesson's practice
- Key types differ.
CreditCardIDandProductSubcategoryIDare stored as different types in the course database, soCAST(... AS VARCHAR)one side before joining. - LEFT JOIN + WHERE on the right table removes the unmatched rows, so it behaves like INNER JOIN.
- Keys that look equal but are not. CRM has
GTXProin the pipeline andGTX Proin products: 729 won 2017 deals silently drop out of HW Q1. - One-to-many multiplies rows. Orders joined to reasons repeat an order per reason. Use DISTINCT or aggregate, then check the row count.
Interview favourites Two "same result" questions
- INNER = LEFT? Yes:
LEFT JOIN ... WHERE right.key IS NOT NULLreturns exactly the INNER JOIN rows. - FULL = LEFT + RIGHT? Yes: LEFT JOIN, then
UNIONthe RIGHT JOIN. UNION removes the matched rows that appear in both.
Try both in the JOIN lab.
Map Tables used in Lesson 3
Orange = fact table (many rows). Blue = dimension. Arrow label = join key. ⚠ = stored with different data types in the course database, so CAST one side.
Lab See what each JOIN keeps
Illustrative mini tables. Pick a join and watch which rows survive. Order 105 has a NULL territory: NULL never equals anything, so it never matches.