Bitpath

Lesson 2 · Unit 01

Joins

Follow keys from one table to another

12 exercisesabout 3 min

What you practise

  • Primary and foreign keys, INNER JOIN, LEFT JOIN and its NULLs, one-to-many and many-to-many through a join table, how a join multiplies rows

Try a question from this lesson

Pick one

Orders store a user_id, not the buyer's email. Ana has 500 orders and changes her email. How many rows must be updated?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Keys connect tables

A primary key identifies one row: users.id. A foreign key is a column holding another table's key: orders.user_id.

JOIN ... ON lines two tables up wherever the keys match and gives you one row per matching pair.

SQL
CREATE TABLE users(id, name);
CREATE TABLE orders(id, user_id, total);
INSERT INTO users VALUES
  (1, 'Ana'), (2, 'Bo'), (3, 'Cy');
INSERT INTO orders VALUES
  (1, 1, 30), (2, 1, 20), (3, 2, 50);
SELECT name, total FROM users
JOIN orders
  ON orders.user_id = users.id
ORDER BY total;

Concept

Many-to-many needs a third table

A student takes many courses, and a course has many students. Neither table can hold the other's key in a single column.

The fix is a join table with one row per link: enrollments(student_id, course_id). Student 1 is in courses 10 and 11, so there are two rows for student 1.

SQL
CREATE TABLE students(id, name);
CREATE TABLE courses(id, title);
CREATE TABLE enrollments(
  student_id, course_id);
INSERT INTO enrollments VALUES
  (1, 10), (1, 11), (2, 10);

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy