Machine Room

SQL Joins

Every join, on three customers and five orders. The one-page notes from the reel.

Download the PDF

One-page notes on SQL joins: Emma, Jack and Lily in a customers table, five orders in an orders table, orders 4 and 5 guest checkouts with a NULL customer_id; Emma has no orders, Jack has one, Lily has two. The query customers c ___ JOIN orders o ON o.customer_id = c.id, then each join as two overlapping circles, customers and orders: INNER JOIN fills only the overlap, only rows that match on both sides, no match means no row, used for each order next to the customer who placed it; LEFT JOIN fills the whole customers circle, every customer matched or not, NULL on the order side, and adding WHERE o.id IS NULL leaves only the customers who never ordered; RIGHT JOIN fills the whole orders circle, every order matched or not, NULL on the customer side, the same result as orders LEFT JOIN customers, which is how it is usually written; FULL JOIN fills both circles, everything from both sides, NULL on whichever side is missing, used for checking two tables against each other; CROSS JOIN draws a line from every customer to every order, 3 × 5 = 15 rows, no ON, used for every combination like sizes S, M, L × colours black, white. What the circles don't show: after the LEFT JOIN COUNT(name) = 4 although there are only 3 customers, because Lily has two orders and is counted twice; the fix is COUNT(DISTINCT name) = 3. Same two tables: the join you pick decides which rows come back.

On a phone, press and hold the image to save it. The reel: SQL Joins Explained: INNER, LEFT, RIGHT, FULL and CROSS JOIN.