A FULL OUTER JOIN in SQL is a type of join that combines the principles of both LEFT JOIN and RIGHT JOIN. It returns all rows from both the left and the right tables, filling in with NULL
values where there is no match between the tables. This type of join is crucial for scenarios where you need to understand all potential relationships and discrepancies between two datasets, making it ideal for comprehensive data analysis that leaves no entry behind.
FULL OUTER JOINS are particularly useful when you need a complete picture from both tables, regardless of whether the rows match. This can be vital in data reconciliation processes, merging datasets from different sources, or when preparing comprehensive reports that require listing all data points from interconnected tables.
To illustrate the use of FULL OUTER JOIN, let’s consider two tables, Orders
and Shipments
, which log orders and their respective shipments.
OrderID | CustomerName |
---|---|
1 | John Doe |
2 | Jane Smith |
3 | Sam Brown |
ShipmentID | OrderID | ShipDate |
---|---|---|
101 | 1 | 2024-04-25 |
102 | 3 | 2024-04-26 |
103 | 4 | 2024-04-27 |
Objective: Match orders with their shipments and display all orders and shipments, noting any discrepancies.
SQL Query:
SELECT Orders.OrderID, Orders.CustomerName, Shipments.ShipDate
FROM Orders
FULL OUTER JOIN Shipments ON Orders.OrderID = Shipments.OrderID;
How It Works:
FULL OUTER JOIN
clause is used to combine the Orders
table with the Shipments
table.ON
condition specifies that rows should match based on OrderID
.Expected Output:
OrderID | CustomerName | ShipDate |
---|---|---|
1 | John Doe | 2024-04-25 |
2 | Jane Smith | NULL |
3 | Sam Brown | 2024-04-26 |
NULL | NULL | 2024-04-27 |
This output includes all orders and shipments. Notice that:
Objective: Identify all orders that have not been shipped yet and all shipments that do not match any existing order.
SQL Query:
SELECT Orders.OrderID, Orders.CustomerName, Shipments.ShipDate
FROM Orders
FULL OUTER JOIN Shipments ON Orders.OrderID = Shipments.OrderID
WHERE Orders.OrderID IS NULL OR Shipments.ShipDate IS NULL;
How It Works:
WHERE
clause that filters the results to show only unmatched rows from either table.Expected Output:
OrderID | CustomerName | ShipDate |
---|---|---|
2 | Jane Smith | NULL |
NULL | NULL | 2024-04-27 |