Assignment Review & JOINs: Inner, Left, Right, Full, Cross
Combining data from several tables, then analysing the combined result with grouping and filters.
1. The Crux in 60 Seconds
Joins merge tables
Real data lives in several tables. A join pairs rows from two tables on a matching column so you can read them together, like Excel's VLOOKUP.
Pick the join by what you keep
INNER keeps matches only; LEFT keeps every left row; RIGHT every right row; FULL both sides; CROSS pairs every row with every row.
Alias every table
Use o.order_id, r.order_id. Without a prefix a column present in both tables is ambiguous and errors.
Join, then filter and group
The join runs right after FROM and before WHERE. After it, think of the result as one big table for GROUP BY, HAVING and the rest.
2. Foundational Concepts & Comparisons
Excel VLOOKUP
- Looks up an order ID in another sheet and fetches its return reason
- Shows NA where the order was not returned
- Goal: lost sales by return reason, which needs both datasets side by side
SQL join
- Matches rows on the join column (order ID) in both tables
- Shows NULL where there is no match (in a left join)
- Then aggregate as usual: total sales per return reason
Join types at a glance (employee table: 10 rows; department table: 4 rows)
| Join | What comes out | Rows in the class demo |
|---|---|---|
| INNER | Only rows whose department ID exists on both sides | 9 (department 500 has no match) |
| LEFT (employee left) | All employees; department data NULL when missing | 10 |
| RIGHT | All departments; employee data NULL when missing | 10 (department 400 has no employee) |
| FULL OUTER | All matches plus unmatched rows from both sides | 11 |
| CROSS | Every row paired with every row; no condition | 40 (10 x 4) |
The two demo tables
- Employee: employee ID, name, department ID, salary, manager ID (10 rows)
- Department: department ID, department name (4 rows); for example ID 100 is analytics
- Employees use IDs 100, 200, 300 and 500; departments hold 100, 200, 300 and 400, so each side has one unmatched value
Join vs union
A student asked how FULL OUTER JOIN differs from UNION. The instructor: completely different things; he will explain when UNION is taught, to avoid confusing everyone now.