Database.Beginner.FullOuterJoin

FULL OUTER JOIN Explained

A FULL OUTER JOIN:

  • Returns all records from both tables.
  • If there’s a match between A and B, it combines them.
  • If there’s no match, you still get the row — with NULL in the missing side.

Summary:

SituationFULL OUTER JOIN behavior
Row matches in both A and BCombine them.
Row in A, but no match in BShow A row + NULL for B.
Row in B, but no match in AShow B row + NULL for A.

Example

Customers

customer_idname
1Alice
2Bob
3Charlie

Orders

order_idcustomer_idproduct
1011Laptop
1022Smartphone
1034Tablet

Query:

SELECT Customers.customer_id, Customers.name, Orders.order_id, Orders.product
FROM Customers
FULL OUTER JOIN Orders
ON Customers.customer_id = Orders.customer_id;

Result:

customer_idnameorder_idproduct
1Alice101Laptop
2Bob102Smartphone
3CharlieNULLNULL
NULLNULL103Tablet

What’s happening:

  • Alice and Bob match an order — perfect, rows are merged.
  • Charlie has no orders — so we see his row with NULL for order_id and product.
  • Order 103 is for customer_id = 4, but no such customer — so customer_id and name are NULL on the left side.

Why Use FULL OUTER JOIN?

  • When you want to see everything: all customers, all orders — even if there’s no match.
  • Useful for reporting, audits, or finding mismatches (like customers without orders, or orders without customers).

For example:

  • Customers who haven’t ordered anything yet.
  • Orders placed but no matching customer exists (e.g., data entry errors).

FULL OUTER JOIN = LEFT JOIN + RIGHT JOIN

You could think of it as:

SELECT * FROM Customers
LEFT JOIN Orders ON Customers.customer_id = Orders.customer_id
UNION
SELECT * FROM Customers
RIGHT JOIN Orders ON Customers.customer_id = Orders.customer_id;

But FULL OUTER JOIN does this in one step.


Limitations

  • Not supported by all databases natively (e.g., MySQL doesn’t support FULL OUTER JOIN directly — you have to simulate it with UNION of LEFT JOIN and RIGHT JOIN).

Visual (Venn Diagram)

     🟢 (Customers)      🔵 (Orders)
         \_________intersection_________/

FULL OUTER JOIN = 🟢 everything in both circles 🔵


Would you like me to show how to simulate a FULL OUTER JOIN in MySQL (since MySQL doesn’t have a direct FULL OUTER JOIN keyword)? 🚀✨

This entry was posted in Без рубрики. Bookmark the permalink.