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

CustomerNameOrderIDOrderCustomerID
Fjord SuppliesNULLNULL
Harbor LightsNULLNULL
Aarav Traders1011
Delta Mart1024
Blue Harbor Foods1032
Aarav Traders1041
Evergreen Grocers1055
Cedar & Co1063
Delta Mart1074
Golden Spoon1087
NULL10999

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

CustomerNameOrderID
Aarav Traders101
Aarav Traders104
Blue Harbor Foods103
Cedar & Co106
Delta Mart102
Delta Mart107
Evergreen Grocers105
Fjord SuppliesNULL
Golden Spoon108
Harbor LightsNULL
NULL109

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.