FULL (OUTER) JOIN
The SQL FULL OUTER JOIN
FULL OUTER JOIN returns all records when there is a match in either the left or the right table. Rows without a partner get NULL on the other side.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;Note: FULL OUTER JOIN can return very large result sets. FULL JOIN and FULL OUTER JOIN are the same.
Example
Example
Customers and orders, keeping customers without orders and orders without a known customer. We add one order for a deleted customer (ID 99):
INSERT INTO Orders (OrderID, CustomerID, EmployeeID, OrderDate, Amount)
VALUES (109, 99, 3, '2024-04-10', 75);
SELECT c.CustomerName, o.OrderID, o.CustomerID AS OrderCustomerID
FROM Customers c
FULL OUTER JOIN Orders o ON o.CustomerID = c.CustomerID
ORDER BY o.OrderID;Result: 11 rows
| CustomerName | OrderID | OrderCustomerID |
|---|---|---|
| Fjord Supplies | NULL | NULL |
| Harbor Lights | NULL | NULL |
| Aarav Traders | 101 | 1 |
| Delta Mart | 102 | 4 |
| Blue Harbor Foods | 103 | 2 |
| Aarav Traders | 104 | 1 |
| Evergreen Grocers | 105 | 5 |
| Cedar & Co | 106 | 3 |
| Delta Mart | 107 | 4 |
| Golden Spoon | 108 | 7 |
| NULL | 109 | 99 |
Note: The code runner uses an older SQLite (3.27) that does not support RIGHT or FULL joins, so Run on this example fails there. The result shown is from SQLite 3.39+, which gives the same answer as PostgreSQL and SQL Server.
Uses
- Reconciling two lists, e.g. bank statement vs. accounting entries: what is only in one, only in the other, or in both.
- Comparing a table before and after a data migration.
- Merging two sources where either side may be missing a record.
MySQL Has No FULL JOIN
MySQL (and SQLite before 3.39) do not support FULL OUTER JOIN. Emulate it with a LEFT JOIN plus the right-side rows that did not match, combined with UNION ALL.
Example
Add an order whose customer (ID 99) does not exist, then combine both sides:
INSERT INTO Orders (OrderID, CustomerID, EmployeeID, OrderDate, Amount)
VALUES (109, 99, 3, '2024-04-10', 75);
SELECT c.CustomerName, o.OrderID
FROM Customers c
LEFT JOIN Orders o ON o.CustomerID = c.CustomerID
UNION ALL
SELECT NULL, o.OrderID
FROM Orders o
WHERE NOT EXISTS (SELECT 1 FROM Customers c WHERE c.CustomerID = o.CustomerID);Result: 11 rows
| CustomerName | OrderID |
|---|---|
| Aarav Traders | 101 |
| Aarav Traders | 104 |
| Blue Harbor Foods | 103 |
| Cedar & Co | 106 |
| Delta Mart | 102 |
| Delta Mart | 107 |
| Evergreen Grocers | 105 |
| Fjord Supplies | NULL |
| Golden Spoon | 108 |
| Harbor Lights | NULL |
| NULL | 109 |
Why UNION ALL and Not UNION?
The second query only returns orders whose customer does not exist, so the two halves can never overlap. UNION ALL skips the expensive duplicate check, and it will not wrongly merge two genuinely identical rows.