LEFT JOIN to Keep Rows with No Match
Lesson 10 of 33 in the SQL / MySQL learning path.
How do I list every user even when they have no enrollment?
A directory of students is a different question from a class list. Every user should appear, including a person who has not registered for a course. LEFT JOIN keeps the left table, here users, and fills the course columns with null when no enrollment matches. Ada still appears twice, once per course. Alan appears once, with a null course code and a null title, because he has an account and no registration.
A second query keeps that left join and then keeps only the rows where the enrollment id is null. That is the list of students who have not enrolled. The filter has to test the right-hand key for null. Putting a course code test in WHERE instead of ON throws away the unmatched students and the join behaves like an inner join. This script creates the three tables so it runs alone.
Syntax & Parameters
SELECT column_list
FROM users AS u
LEFT JOIN enrollments AS e ON e.user_id = u.id
LEFT 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');
INSERT INTO courses (code, title, seats) VALUES
('CS101', 'Intro to Databases', 30),
('CS220', 'Relational Design', 24);
INSERT INTO enrollments (user_id, course_id, enrolled_on) VALUES
(1, 1, '2026-01-20'),
(1, 2, '2026-01-21'),
(2, 1, '2026-01-20');
SELECT u.id, u.name, c.code, c.title
FROM users AS u
LEFT JOIN enrollments AS e ON e.user_id = u.id
LEFT JOIN courses AS c ON c.id = e.course_id
ORDER BY u.id, c.code;
SELECT u.id, u.name
FROM users AS u
LEFT JOIN enrollments AS e ON e.user_id = u.id
WHERE e.id IS NULL
ORDER BY u.id;
Expected Output
Directory, including the student with no course id | name | code | title 1 | Ada Lovelace | CS101 | Intro to Databases 1 | Ada Lovelace | CS220 | Relational Design 2 | Grace Hopper | CS101 | Intro to Databases 3 | Alan Turing | NULL | NULL 4 rows in set Students with no enrollment id | name 3 | Alan Turing 1 row in set
Line-by-Line Walkthrough
- The script creates users, courses, and enrollments, then loads Ada, Grace, and Alan.
- Ada is enrolled in CS101 and CS220. Grace is enrolled in CS101. Alan has no enrollment row.
- LEFT JOIN enrollments keeps every user. The ON clause still requires e.user_id = u.id for a real match.
- The second LEFT JOIN brings in the course. When Alan has no enrollment, both course columns are null.
- Ada produces two result rows because she has two matches. A left join does not collapse those rows.
- ORDER BY u.id, c.code lists Ada, then Grace, then Alan, because those are user ids 1, 2, and 3. Alan is last because of his id. MySQL sorts a null course code before real codes, so the id is what places him.
- The second SELECT is the anti-join: the same left join, plus WHERE e.id IS NULL, which keeps only Alan.
- The null test must use the right-hand key. A test on u.id would be true for every student and would not find the unmatched ones.
- WHERE c.code = CS101 would discard Alan, because null equals CS101 is unknown, and it would also discard Ada's CS220 row. That WHERE turns the left join back into an inner join for the kept rows.
- COUNT(*) on this left join counts result rows, so Ada counts twice and Alan counts once. COUNT of e.id ignores Alan. COUNT DISTINCT u.id counts students.
Common Pitfalls & Security
LEFT JOIN keeps the students, and a filter in the wrong clause gives them back. The ON clause decides which right-hand row matches. The WHERE clause decides which of those results survive. A predicate on the course, placed in WHERE, rejects the null-extended rows. Count carefully: the join can emit more than one row per student, and a null-extended student is a row whose enrollment columns are null.
- WHERE c.code = 'CS101' after a left join drops Alan and drops Ada second course. Put a filter that should preserve unmatched users in the ON clause, or apply it only when you mean an inner join.
- WHERE e.id IS NULL finds students with no enrollment. WHERE e.id = NULL finds nobody, because equality with null is unknown.
- COUNT(*) counts Ada twice. Use COUNT(DISTINCT u.id) for a headcount of users, and COUNT(e.id) for a headcount of registrations, which skips Alan.
- A left join does not invent a course. Null means no match. The application should show an empty class list, not the word NULL, if that is what staff should read.
- Selecting password_hash on a directory page exposes the hash. List id, name, and the course columns.
- An UPDATE or DELETE without WHERE is a catastrophe. Do not repair unmatched students by updating every row. This lesson only reads.
Best Practices & Modern Standards
Use LEFT JOIN when the driving table is the one that must survive, and test the right-hand key with IS NULL when you want the unmatched rows only. Keep course filters that still mean "this course" in a place that matches the question: ON when unmatched students must remain, WHERE when you are willing to drop them. Count distinct user ids when the report is a headcount.
The inner join lesson is the class list. This lesson is the directory. Aggregates on a left join need COUNT of the right-hand id so a student with no enrollment contributes zero. A subquery can answer the same unmatched question, and the next lessons compare those shapes.
Real-World Use
Orientation staff need every student in users, plus the courses they have joined through enrollments. Students who have not chosen a course yet must still be on the checklist, with a blank class column. LEFT JOIN produces that sheet. A follow-up filter on a null enrollment id is the call list of students who still need to register. The course catalog itself stays in courses and is not deleted just because someone has an empty schedule.
Frequently Asked Questions
Why is Alan in the first result and Katherine was missing from the inner join?
LEFT JOIN keeps every row from users. Alan has no enrollment, so his course columns are null and he still appears. An inner join would have removed him the way the previous lesson removed a student with no registration.
How do I list only students who have no course?
Left join enrollments and add WHERE e.id IS NULL. That keeps the user rows that found no match. The second query in the sample returns Alan and nobody else.
Why did filtering the course code drop the unmatched student?
WHERE runs after the join. A null course code does not equal CS101, so the unmatched row is rejected. The result then contains only real CS101 registrations, which is an inner-join outcome.
Does a left join return one row per student?
It returns one row per match, and one null-extended row when there is no match. Ada has two courses, so she appears twice. Collapse with GROUP BY or ask a separate headcount when the page needs one line per student.