JOINs — Combining Tables
JOIN is arguably the most important SQL operation. It lets you combine rows from two tables based on a related column. Mastering JOINs means you can answer questions that span multiple tables.
Key Concepts
INNER JOIN
INNER JOIN returns only rows that have a match in BOTH tables. SELECT students.name, courses.title FROM enrollments INNER JOIN students ON enrollments.student_id = students.id INNER JOIN courses ON enrollments.course_id = courses.id.
LEFT JOIN
LEFT JOIN returns ALL rows from the left table, plus matching rows from the right. If there is no match, the right side shows NULL. This is useful for 'find students who have NOT enrolled in any course.'
Foreign Keys
A foreign key is a column that references the primary key of another table. enrollment.student_id is a foreign key pointing to students.id. This relationship is what makes the JOIN possible and what enforces referential integrity.
🆕 JOIN Visualizer
See how INNER JOIN and LEFT JOIN work on sample tables.
✅ Check Your Understanding
1. What does INNER JOIN return?
2. When would you use LEFT JOIN instead of INNER JOIN?
3. What is a foreign key?