Combining Data from Multiple Tables
In a well-designed database, data is spread across multiple tables to avoid redundancy. JOINs allow you to combine rows from two or more tables based on related columns.
Types of JOINs
Students Enrollments
ββββββ¬ββββββββββ ββββββ¬ββββββββββ¬βββββββ
β ID β Name β βSID βCourseID βGrade β
ββββββΌββββββββββ€ ββββββΌββββββββββΌβββββββ€
β 1 β Alice β β 1 β 101 β A β
β 2 β Bob β β 2 β 101 β B β
β 3 β Charlie β β 3 β 102 β A β
β 4 β Diana β ββββββ΄ββββββββββ΄βββββββ
ββββββ΄ββββββββββ
INNER JOIN β Only rows that match in both tables:
SELECT Students.Name, Enrollments.CourseID, Enrollments.Grade
FROM Students
INNER JOIN Enrollments ON Students.ID = Enrollments.SID;
Result:
βββββββββββ¬ββββββββββ¬βββββββ
β Name βCourseID βGrade β
βββββββββββΌββββββββββΌβββββββ€
β Alice β 101 β A β
β Bob β 101 β B β
β Charlie β 102 β A β
βββββββββββ΄ββββββββββ΄βββββββ
(Diana excluded β no enrollment)
LEFT JOIN β All rows from the left table, matching rows from right (NULL if no match):
RIGHT JOIN β All rows from the right table, matching rows from left.
FULL OUTER JOIN β All rows from both tables (NULL where no match).
Self Join
-- Find employees and their managers
SELECT E.Name AS Employee, M.Name AS Manager
FROM Employees E
LEFT JOIN Employees M ON E.ManagerID = M.ID;