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
isHR
. - Bob: He belongs to the IT department (DepartmentID 102), so the
DepartmentName
isIT
. - Charlie: There is no matching
DepartmentID
103 in theDepartments
table, soDepartmentName
isNULL
. - Eve: She does not have a
DepartmentID
, soDepartmentName
isNULL
.
The LEFT JOIN
ensures all employees are included in the result, even if they do not have a corresponding department.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.