Databases / SQL joins

SQL joins

Two tiny tables, one matching rule, and the exact rows each kind of join returns: inner, left, right, full outer and cross.

Beginner7 steps~6 min
customers — the left table: one row per customer
orders — the right table: each row names a customer id
Result — the rows a join returns
NULL — no value: the other table had no match
// THE SHORT VERSION

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

STEPS01 / 07

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 01 / 07 Two tables
THE MATH
customers(id, name) orders(id, customer_id, item)
  1. 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.
  2. 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.
  3. 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.
  4. 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”.
  5. 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.
  6. 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.
  7. 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.
VALUES SO FAR
left3 customersinput
right4 ordersinput
matches····rule
INNER····result
LEFT····result
RIGHT····result
FULL····result
CROSS····result
Ana····trap
// BEFORE

Learn this first

Nothing. This concept starts from scratch.

Spotted a mistake on this page?