appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Joining tables

Lesson 3 of 410 minBeginner

Primary and foreign keys, INNER and LEFT JOIN.

Data is split across tables to avoid repeating it. A primary key uniquely identifies a row. A foreign key in another table points to it. Suppose orders has user_id pointing to users.id:

order iduser_idtotal
10125
11140
12315

INNER JOIN

SELECT users.name, orders.total
FROM users
INNER JOIN orders ON orders.user_id = users.id;

It returns only users that have orders: Ana (twice) and Chen. Bob and Dara do not appear.

LEFT JOIN

SELECT users.name, orders.total
FROM users
LEFT JOIN orders ON orders.user_id = users.id;

It keeps every user and fills NULL where there is no order, so Bob and Dara appear with a missing total. This is how you find users without orders: add WHERE orders.user_id IS NULL.

NoteAlways write the ON condition. Forgetting it can produce every row paired with every other row (a cross join).

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which join keeps all rows from the left table even without a match?
2. What is a foreign key?
3. With the tables above, how many rows does the INNER JOIN return?
4. How do you find users that have no orders?

Key terms