SQL Tutorial
A FULL JOIN
in SQL returns all records when there is a match in either the left (table1) or the right (table2) table records. Essentially, it combines the functions of a LEFT JOIN
and a RIGHT JOIN
.
Here's the basic syntax:
SELECT column_name(s) FROM table1 FULL JOIN table2 ON table1.column_name = table2.column_name;
The FULL JOIN
keyword returns all records from both tables, and fills in NULL
for missing matches on either side.
Example:
Consider the following two tables:
Orders
table:
OrderID | CustomerID | OrderAmount |
---|---|---|
1 | 3 | 100 |
2 | 1 | 160 |
3 | 2 | 70 |
4 | 5 | 240 |
Customers
table:
CustomerID | Name |
---|---|
1 | John |
2 | Jane |
3 | Alice |
4 | Bob |
If we want to select all orders, and any matching customer information, we can use a FULL JOIN
like this:
SELECT Orders.OrderID, Customers.Name, Orders.OrderAmount FROM Orders FULL JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
This would return:
OrderID | Name | OrderAmount |
---|---|---|
1 | Alice | 100 |
2 | John | 160 |
3 | Jane | 70 |
4 | NULL | 240 |
NULL | Bob | NULL |
As you can see, it has returned all records from both Orders
and Customers
. Where there are no matching values, the result is NULL
.
Note: Not all database systems support FULL JOIN
. However, you can achieve similar results by combining LEFT JOIN
and RIGHT JOIN
, or by using a UNION
of a LEFT JOIN
and a RIGHT JOIN
.
As always, the exact syntax may vary between different SQL dialects, so be sure to consult the documentation for the SQL dialect you're using.
Combining Rows from Multiple Tables with FULL JOIN:
SELECT * FROM Table1 FULL JOIN Table2 ON Table1.ID = Table2.ID;
SQL FULL OUTER JOIN Example:
SELECT * FROM Table1 FULL OUTER JOIN Table2 ON Table1.ID = Table2.ID;
FULL JOIN vs INNER JOIN vs LEFT JOIN:
Description: FULL JOIN returns all rows from both tables, INNER JOIN returns only matching rows, and LEFT JOIN returns all rows from the left table and matching rows from the right table.
Code Example (INNER JOIN):
SELECT * FROM Table1 INNER JOIN Table2 ON Table1.ID = Table2.ID;
Code Example (LEFT JOIN):
SELECT * FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.ID;
Using WHERE Clause with FULL JOIN:
SELECT * FROM Table1 FULL JOIN Table2 ON Table1.ID = Table2.ID WHERE Table1.Column1 = 'Value';
Handling NULL Values in SQL FULL JOIN:
SELECT COALESCE(Table1.Column1, 'DefaultValue') AS ResultColumn FROM Table1 FULL JOIN Table2 ON Table1.ID = Table2.ID;
Multiple Tables FULL JOIN in SQL:
SELECT * FROM Table1 FULL JOIN Table2 ON Table1.ID = Table2.ID FULL JOIN Table3 ON Table1.ID = Table3.ID;
SQL FULL JOIN with Multiple Conditions:
SELECT * FROM Table1 FULL JOIN Table2 ON Table1.ID = Table2.ID AND Table1.Column1 = Table2.Column1;