Joins and Combining Tables
INNER, LEFT, FULL and self joins, set operations, and how to avoid the row-duplication bugs that ruin totals.
Beginner · about 6 hours · difficulty 3/5
Learn first: Aggregation with GROUP BY and HAVING
Real questions span tables: orders need customers, products and campaigns. Joins connect them through keys.
Join types
- INNER JOIN: only rows with a match on both sides.
- LEFT JOIN: every row from the left table, with NULLs where the right has no match. The analyst's default when you must not lose records.
- FULL OUTER JOIN: everything from both sides; useful for reconciling two sources.
- CROSS JOIN: every combination; handy for building date-by-product grids.
- Self join: a table joined to itself, e.g. employees to their managers.
Anti joins and set operations
Find customers with no orders using LEFT JOIN ... WHERE o.id IS NULL or NOT EXISTS. UNION ALL stacks results with the same columns; UNION also removes duplicates (and costs more). INTERSECT and EXCEPT compare sets.
Grain and fan-out
Every table has a grain: what one row represents. Joining orders (one row per order) to order_items (many per order) changes the grain, and summing order-level amounts afterwards double-counts. Before joining, ask: "is this key unique on the right side?" Aggregate first, then join, when grains differ.
Filter placement
With LEFT JOIN, a condition on the right table in WHERE turns it into an inner join. Put such conditions in the ON clause instead.
Pitfall: trusting a join without checking row counts before and after. Move on when you can predict the row count of a join before running it.
Key concepts
- INNER and LEFT JOIN
- FULL OUTER and CROSS JOIN
- Self joins
- Anti joins and NOT EXISTS
- UNION ALL, INTERSECT, EXCEPT
- Table grain and fan-out: The most common source of wrong totals
- ON vs WHERE with outer joins
- Joining on multiple keys
Mini project
Using the Brazilian E-Commerce (Olist) dataset on Kaggle, join orders, items, products and reviews to compute average review score by product category without double-counting orders.
Check yourself
You LEFT JOIN customers to orders and add WHERE orders.status = 'paid'. Why did customers with no orders disappear?
Free resources
- SQLBolt (SQLBolt)
- Mode SQL Tutorial (Mode)
- PostgreSQL tutorial: joins (PostgreSQL)