SQL: difference between INNER JOIN, LEFT JOIN and RIGHT JOIN?

posée 5 months ago307 vuesen

5

I have students and enrollments. Some students have no enrollment. Which JOIN shows all students, including those without enrollments?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 5 months ago

2 réponses

7
✓
✓ Réponse acceptée

- INNER JOIN: only rows that match in both tables. Students without enrollments disappear. - LEFT JOIN: all rows from the left table, plus matches from the right. Where there's no match, the right-side columns are NULL. - RIGHT JOIN: the mirror of LEFT. Rarely used, since you can just swap the table order.

SELECT s.name, e.course_id
FROM students s
LEFT JOIN enrollments e ON e.student_id = s.id;

To find students with no enrollment:

SELECT s.*
FROM students s
LEFT JOIN enrollments e ON e.student_id = s.id
WHERE e.student_id IS NULL;

Careful: a condition on the right table in WHERE (e.g. WHERE e.year = 2026) turns your LEFT JOIN back into an INNER JOIN. Put it in the ON clause instead.

Connectez-vous pour dire si ça a marché.

answered 5 months ago
0

A visual trick that helps: draw both tables as circles. INNER = the overlap only; LEFT = the whole left circle plus the overlap. Keep in mind the analogy breaks down with duplicates: a LEFT JOIN can return *more* rows than the left table if one student has several enrollments.

Connectez-vous pour dire si ça a marché.

answered 5 months ago

Sign in and verify your email to post an answer.