INNER JOIN Across Users, Courses, and Enrollments
Lesson 9 of 33 in the SQL / MySQL learning path.
How do I combine matching rows from related tables?
A class list is not stored as one wide row. The student name lives in users, the course title lives in courses, and the fact that this student took this course lives in enrollments. INNER JOIN keeps a row only when the key match succeeds. This lesson walks two hops: users to enrollments on user id, then enrollments to courses on course id. The result is one line per registration, with the student and the course beside it.
Katherine has a user account and no enrollment, so she is absent from the result. That is what an inner join means. Alan, Ada, and Grace appear once for every course they take. The sample creates all three tables, including enrollments, so the script runs by itself. An application that loads students and then loads each course inside a loop is the problem laravel-eager-loading is meant to avoid. The SQL here is the set-based form of that roster.
Syntax & Parameters
SELECT column_list
FROM users AS u
INNER JOIN enrollments AS e ON e.user_id = u.id
INNER JOIN courses AS c ON c.id = e.course_id;
Example
CREATE DATABASE IF NOT EXISTS school CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE school;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS courses;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(120) NOT NULL,
email VARCHAR(254) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE courses (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
code VARCHAR(16) NOT NULL,
title VARCHAR(160) NOT NULL,
seats SMALLINT UNSIGNED NOT NULL DEFAULT 30,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_courses_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE enrollments (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
course_id INT UNSIGNED NOT NULL,
enrolled_on DATE NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_enrollments_user_course (user_id, course_id),
CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT fk_enrollments_course FOREIGN KEY (course_id) REFERENCES courses (id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO users (name, email, password_hash, created_at) VALUES
('Ada Lovelace', 'ada@school.test', 'sample-hash-not-a-secret', '2026-01-15 09:00:00'),
('Grace Hopper', 'grace@school.test', 'sample-hash-not-a-secret', '2026-02-11 09:30:00'),
('Alan Turing', 'alan@school.test', 'sample-hash-not-a-secret', '2026-03-02 11:00:00'),
('Katherine Johnson', 'katherine@school.test', 'sample-hash-not-a-secret', '2026-04-01 09:00:00');
INSERT INTO courses (code, title, seats, created_at) VALUES
('CS101', 'Intro to Databases', 30, '2026-01-10 08:00:00'),
('CS220', 'Relational Design', 24, '2026-01-10 08:05:00'),
('CS310', 'Query Tuning', 18, '2026-01-10 08:10:00');
INSERT INTO enrollments (user_id, course_id, enrolled_on, created_at) VALUES
(1, 1, '2026-01-20', '2026-01-20 09:00:00'),
(2, 1, '2026-01-20', '2026-01-20 09:05:00'),
(3, 1, '2026-01-20', '2026-01-20 09:10:00'),
(1, 2, '2026-01-21', '2026-01-21 09:00:00'),
(2, 2, '2026-01-21', '2026-01-21 09:05:00'),
(3, 3, '2026-01-22', '2026-01-22 09:00:00');
SELECT u.name, u.email, c.code, c.title, e.enrolled_on
FROM users AS u
INNER JOIN enrollments AS e ON e.user_id = u.id
INNER JOIN courses AS c ON c.id = e.course_id
ORDER BY u.name, c.code;
Expected Output
name | email | code | title | enrolled_on Ada Lovelace | ada@school.test | CS101 | Intro to Databases | 2026-01-20 Ada Lovelace | ada@school.test | CS220 | Relational Design | 2026-01-21 Alan Turing | alan@school.test | CS101 | Intro to Databases | 2026-01-20 Alan Turing | alan@school.test | CS310 | Query Tuning | 2026-01-22 Grace Hopper | grace@school.test | CS101 | Intro to Databases | 2026-01-20 Grace Hopper | grace@school.test | CS220 | Relational Design | 2026-01-21 6 rows in set Katherine Johnson has a users row and no enrollments row, so she is absent.
Line-by-Line Walkthrough
- The script creates users, courses, and enrollments, including the foreign keys, so this file runs on an empty server.
- Four students are inserted. Katherine has no row in enrollments, which is how the inner join demonstrates a missing match.
- Six enrollment rows connect Ada and Grace to CS101 and CS220, Alan to CS101 and CS310, and nobody to Katherine.
- The first hop is INNER JOIN enrollments ON e.user_id = u.id. A user with no enrollment produces no output row.
- The second hop is INNER JOIN courses ON c.id = e.course_id. Each registration picks up the course code and title.
- The SELECT list names the student, the email, the course, and the enrolled date. It does not use a star.
- ORDER BY u.name, c.code makes the roster stable: Ada, then Alan, then Grace, with each person courses in code order.
- The result has six rows, one per enrollment. Ada appears twice because she takes two courses. Katherine appears zero times.
- A missing ON clause would pair every user with every enrollment. The ON predicate is what keeps the hop meaningful.
- Eloquent code that loads these same relationships without a loop of extra queries is the subject of laravel-eager-loading. The join above is the set the roster needs.
Common Pitfalls & Security
An inner join answers "who is enrolled", and it quietly drops students who are not. That is correct for a class list and wrong for a directory of every account. Each hop needs its own ON. Selecting every column from three tables also drags password_hash into a roster. Name the columns, and expect one output row per enrollment, so a student in two courses appears twice.
- Forgetting ON, or joining ON a condition that is always true, builds a Cartesian product: every student paired with every enrollment. The row count explodes and the list is meaningless.
- INNER JOIN removes Katherine because she has no match. Use a left join, covered next, when the directory must keep students who have not registered.
- Joining enrollments twice, or joining an extra table without a new key, multiplies rows. A student in two courses is already two rows. Another careless join doubles that again.
- SELECT * on users includes password_hash. List name, email, course code, title, and enrolled_on.
- An UPDATE or DELETE without WHERE is a catastrophe. A join does not make a wide update safe. This lesson only reads.
- The unique key stops two enrollment rows for the same student and course. Without it, the join would list that registration twice.
Best Practices & Modern Standards
Join from the child that represents the fact you are listing. For a roster, start at users or at enrollments, and hop to the other side on the foreign key. Keep one ON predicate per hop, select only the columns the page shows, and order by student and course so the list is stable. Create enrollments in the same script when you want the example to run alone.
When an application loads many students and their courses, do that work in one query or in a planned second query, which is the idea behind laravel-eager-loading. The foreign-key lesson is what stops an enrollment from pointing at a missing user or a missing course.
Real-World Use
The enrollment office prints a sheet of students and the courses they take. The student is a row in users, the class is a row in courses, and the registration is a row in enrollments. Two inner joins assemble that sheet. A student who has an account and has not registered for anything is absent, which is what the office wants on a class list and what a directory page would handle with a left join instead.
Frequently Asked Questions
Why does Katherine not appear?
INNER JOIN keeps only matching rows. Katherine has no enrollments row, so the first hop fails and she is left out. She is still in users. A left join keeps her and shows null course columns.
Why does Ada appear twice?
Ada has two enrollment rows, CS101 and CS220. The join outputs one result row per match. A class list that wants one line per registration should look like this. A list of distinct students would group or use DISTINCT.
Do the tables have to contain foreign keys for INNER JOIN to work?
The join compares values. It works without a foreign key, and a foreign key is what stops bad values from being stored. This sample creates the keys so the rows you join are real references.
How is this related to eager loading in Laravel?
A loop that queries courses once per student repeats this lookup many times. Eager loading fetches the related enrollments and courses in bulk. laravel-eager-loading shows that application pattern. The SQL here is the roster those rows represent.