SQL joins
Two tiny tables, one matching rule, and the exact rows each kind of join returns: inner, left, right, full outer and cross.
In 30 seconds
A join combines rows from two tables. You give it a condition, usually “this column equals that column”, and it pairs up the rows for which the condition is true.
The kinds of join differ in what happens to rows with no partner. Inner drops them. Left and right keep them from one side, full outer from both, filling the missing half with NULL.
A row with several partners appears several times, which quietly inflates counts and sums.
SQL joins, step by step
A result has no guaranteed row order without ORDER BY; rows are listed here in a convenient order. MySQL has no FULL OUTER JOIN.
- Step 1: Two tables. A shop keeps customers in one table and orders in another. Each order stores only the id of the customer who placed it, so the question “who ordered what” needs both tables at once.
- Step 2: The join condition. A join pairs a row from one table with a row from the other wherever a condition is true. Here: the order’s customer_id equals the customer’s id. Three pairs pass the test; Cy and order 13 find no partner.
- Step 3: Inner join. An inner join (plain JOIN) returns only the pairs that satisfy the condition: three rows. Cy and the mug order vanish from the result, because neither has a partner.
- Step 4: Left join. A left join keeps every row of the left table, customers, matched or not. Cy has no order, so the order columns in his row are filled with NULL, the database’s marker for “no value”.
- Step 5: Right and full outer join. A right join is the mirror image: every order is kept, so the mug appears with a NULL name. A full outer join keeps the leftovers of both tables: the three matches, plus Cy, plus the mug.
- Step 6: Cross join. A cross join has no condition: every customer is paired with every order, 3 × 4 = 12 rows. The other joins are this grid with a filter. Leave the condition out of an old-style comma join (FROM customers, orders) and you get all twelve by accident.
- Step 7: The duplicate trap. A join repeats a row once per match. Ana has two orders, so she appears twice. Count or sum the joined rows as if each were one customer and the answer is too big. Count distinct ids, or aggregate the orders before joining.
Try it yourself
Learn this first
Nothing. This concept starts from scratch.
Spotted a mistake on this page?