The FULL OUTER JOIN keyword in SQL is used to return all rows from both tables involved in the join. When there is no match between the tables, NULL values are returned for the columns that don't have a match in the other table.
Syntax:
SELECT column1, column2, ...
FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;
Key Points:
- Combines LEFT and RIGHT JOINs: It includes all records from both tables, whether or not they have a match in the other table.
- Null Handling: If a row from one table does not have a matching row in the other table, the result will include
NULLvalues for the unmatched columns.
Example:
Suppose you have two tables:
Table1: Customers
| CustomerID | Name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Carol |
Table2: Orders
| OrderID | CustomerID |
|---|---|
| 101 | 1 |
| 102 | 4 |
Using a FULL OUTER JOIN:
SELECT Customers.CustomerID, Customers.Name, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
Result:
| CustomerID | Name | OrderID |
|---|---|---|
| 1 | Alice | 101 |
| 2 | Bob | NULL |
| 3 | Carol | NULL |
| 4 | NULL | 102 |
Benefits:
- Useful for analyzing differences and overlaps between two datasets.
- Ensures no data is lost from either table.
Notes:
- Not all database systems support
FULL OUTER JOINnatively. If unavailable, you can simulate it with a combination ofLEFT JOIN,RIGHT JOIN, andUNION.
No comments:
Post a Comment