skipnothing/SQL

INNER JOIN

Three users, four orders: the buyer's name sits in a separate table from the amount. Pair each order with its user by user_id and four matched rows come back; the user who never bought a thing is left out.

  • ▸Pair three users with four orders and four rows return, not three, not seven: the count is the matching pairs.
  • ▸The user who never ordered drops out; a row survives this pairing just when it finds a partner.
  • ▸A single user with two orders produces two result rows, so a join hands back more rows than its table.
BUILDS ON
01

Pair Rows on a Join Condition

Three users sit in one table; four orders sit in another. Each order stores a user_id naming its buyer, but the buyer's actual name lives over in users. To read the name and the amount on one line, you pair the two tables: SELECT name, amount FROM users JOIN orders ON users.id = orders.user_id.

The ON clause is a test, the same kind of true-or-false test a WHERE predicate runs, except it runs on a *pair* of rows, one from each side. The engine checks users.id against orders.user_id and keeps the pairing only where the two are equal. Order 101 carries user_id 1, Ada's id is 1, so (Ada, 101) is a kept pair. Order 103 carries user_id 2, which is Brent, so (Brent, 103) is kept. Each kept pair becomes one combined row, Ada's columns followed by the order's columns, and SELECT reads name and amount from it.

This is an INNER JOIN, and the word JOIN on its own means exactly this inner form. The result is built pair by pair: consider every possible user-and-order combination, keep the ones where the join condition holds, drop the rest. Four pairs hold, so four rows come back.

PAIRING ROWS WHERE THE CONDITION HOLDS

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL