Learning navigation

Code with Animation

INNER JOIN

Combine two tables into one result with INNER JOIN, and see which rows find a partner and which quietly disappear.

SQL5 min readConcept 13 of 44

A join glues rows from two tables

Data lives in separate tables so nothing is stored twice. A join builds one wider table out of two by pairing up rows. You tell the database how to pair them with an ON test.

INNER JOIN keeps a pair only when the ON test is true. A row that finds no partner is left out. INNER is the default, so a plain JOIN means the same thing.

Answers live across tables

A question like "which customer bought a Notebook?" needs the customer name from one table and the item from another. A join is how one query reads both.

Match customers to their orders

SELECT c.name, o.item
FROM customers AS c
INNER JOIN orders AS o
  ON c.id = o.customer_id;

c and o are short names (aliases) for the two tables. The ON test says a customer matches an order when the customer's id equals the order's customer_id.

Asha has two orders, so she appears twice. Ben has one. Chen, Dara and Eli have no orders, so they find no partner and do not appear at all.

Match and mismatch

Switch the ON test to the wrong key and watch the result empty out. Then add the Pune filter and see how WHERE trims the joined rows.

SELECT c.name, o.item
FROM customers AS c
INNER JOIN orders AS o ON c.id = o.customer_id
ORDER BY c.id, o.id;
customers AS c
idintegernametextcitytext
1AshaPune
2BenLeeds
3ChenOslo
4DaraLima
5EliRome
orders AS o
idintegercustomer_idintegeritemtext
1011Notebook
1021Pen
1032Ruler
Result (3 rows)
nametextitemtext
AshaNotebook
AshaPen
BenRuler

INNER JOIN keeps a pair only when the ON test is true. Asha has two orders, so she appears twice. Chen, Dara and Eli have no orders, so they do not appear.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1`customers` has 5 rows and only Asha and Ben have orders (3 orders in all). How many rows does `customers INNER JOIN orders ON c.id = o.customer_id` return?
  2. 2What happens to Chen, who has no orders, in an INNER JOIN with orders?
  3. 3A support ticket has `customer_id` set to NULL. Does `c.id = t.customer_id` match it to any customer?

Remember this

  • A join pairs rows from two tables using an ON test, and INNER JOIN keeps only the pairs where ON is true.
  • A row with no partner is dropped without any error.
  • A row with several partners appears once for each partner.
  • A NULL key never matches, so rows with a NULL key do not survive an INNER JOIN.

Done with this concept?

Mark it complete to track your progress. No login needed.