SQL LEFT JOIN
SQL LEFT JOIN Explained
A LEFT JOIN in SQL returns all the records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side if there is no match.
Basic Syntax
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Example
Let's consider two tables: Employees and Departments.
Employees Table
| EmployeeID |
EmployeeName |
DepartmentID |
| 1 |
Alice |
101 |
| 2 |
Bob |
102 |
| 3 |
Charlie |
103 |
| 4 |
David |
101 |
| 5 |
Eve |
NULL |
Departments Table
| DepartmentID |
DepartmentName |
| 101 |
HR |
| 102 |
IT |
| 104 |
Marketing |
Query Using LEFT JOIN
SELECT Employees.EmployeeID, Employees.EmployeeName, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;
Result
| EmployeeID |
EmployeeName |
DepartmentName |
| 1 |
Alice |
HR |
| 2 |
Bob |
IT |
| 3 |
Charlie |
NULL |
| 4 |
David |
HR |
| 5 |
Eve |
NULL |
Explanation of the Output
- Alice and David: They belong to the HR department (DepartmentID 101), so the
DepartmentName is HR.
- Bob: He belongs to the IT department (DepartmentID 102), so the
DepartmentName is IT.
- Charlie: There is no matching
DepartmentID 103 in the Departments table, so DepartmentName is NULL.
- Eve: She does not have a
DepartmentID, so DepartmentName is NULL.
The LEFT JOIN ensures all employees are included in the result, even if they do not have a corresponding department.