SQL FULL OUTER JOIN
A FULL OUTER JOIN
in SQL combines the results of both LEFT JOIN
and RIGHT JOIN
. It returns all records when there is a match in either left (table1) or right (table2) table records. If there is no match, the result is NULL
on the side that does not have a match.
Here's an example to illustrate this concept:
Suppose we have two tables:
Table 1: Employees
EmpID | Name | DeptID |
---|---|---|
1 | John | 101 |
2 | Jane | 102 |
3 | Alice | 103 |
4 | Bob | NULL |
Table 2: Departments
DeptID | DeptName |
---|---|
101 | HR |
102 | Finance |
104 | Marketing |
Now, let's perform a FULL OUTER JOIN
on these tables based on the DeptID
column:
SELECT Employees.EmpID, Employees.Name, Employees.DeptID, Departments.DeptName
FROM Employees
FULL OUTER JOIN Departments
ON Employees.DeptID = Departments.DeptID;
Output
EmpID | Name | DeptID | DeptName |
---|---|---|---|
1 | John | 101 | HR |
2 | Jane | 102 | Finance |
3 | Alice | 103 | NULL |
4 | Bob | NULL | NULL |
NULL | NULL | 104 | Marketing |
Explanation
- John and Jane have matching
DeptID
in both tables, so their records are fully populated. - Alice has a
DeptID
that doesn't match anyDeptID
in the Departments table, soDeptName
isNULL
. - Bob has no
DeptID
, so bothDeptID
andDeptName
areNULL
. - The
Departments
table has aDeptID
(104) that doesn't match anyDeptID
in the Employees table, soEmpID
andName
areNULL
.
This way, FULL OUTER JOIN
ensures that all records from both tables are included in the result set, with NULL
in places where there is no match.
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.