Labs ICT
โญ Pro Login

Introduction to Joins

Joins are where SQL goes from "handy tool" to "superpower." If you can master joins, you can answer almost any question about your data.

The whole point of a relational database is that data is split across multiple tables. Joins let you bring that data back together when you need it.

Why Do We Need Joins?

Imagine you run a school. You have a table for students and a table for the courses they are enrolled in. If you want to show "which students are in which courses," you need to join those tables together.

Let us set up some data to practice with:

CREATE TABLE courses (
  id INTEGER PRIMARY KEY,
  course_name TEXT NOT NULL,
  teacher TEXT
);

INSERT INTO courses VALUES (1, 'Mathematics', 'Mr. Adamu');
INSERT INTO courses VALUES (2, 'English', 'Ms. Obi');
INSERT INTO courses VALUES (3, 'Science', 'Dr. Yusuf');

CREATE TABLE enrollments (
  student_id INTEGER,
  course_id INTEGER,
  grade TEXT
);

INSERT INTO enrollments VALUES (1, 1, 'A');
INSERT INTO enrollments VALUES (1, 2, 'B');
INSERT INTO enrollments VALUES (2, 1, 'C');
INSERT INTO enrollments VALUES (3, 3, 'A');
INSERT INTO enrollments VALUES (4, 2, 'B');

The Key Concept

Joins work by matching columns between tables. Usually, you match the primary key of one table (like students.id) with a foreign key in another table (like enrollments.student_id).

There are different types of joins, and they behave differently when there is no match. We will cover each one in the coming lessons.

๐Ÿงช Quick Quiz

Which JOIN returns only matching rows from both tables?