SQL FULL OUTER JOIN

SQL FULL OUTER JOIN

Another type of join is called a SQL FULL OUTER JOIN. This type of join returns all rows from the LEFT-hand table and RIGHT-hand table with nulls in place where the join condition is not met.

Syntax

The syntax for the SQL FULL OUTER JOIN is:
SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;
In some databases, the FULL OUTER JOIN keywords are replaced with FULL JOIN.

Visual Illustration

In this visual diagram, the SQL FULL OUTER JOIN returns the shaded area:

The SQL FULL OUTER JOIN would return the all records from both table1 and table2.

Example

Here is an example of a SQL FULL OUTER JOIN:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
FULL OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
This FULL OUTER JOIN example would return all rows from the suppliers table and all rows from the orders table and whenever the join condition is not met, <nulls> would be extended to those fields in the result set.
If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the orders table will display as <null> in the result set. If a supplier_id value in the orders table does not exist in the suppliers table, all fields in the suppliers table will display as <null> in the result set.
Let's look at some data to explain how FULL OUTER JOINS work:
We have a table called suppliers with two fields (supplier_id and supplier_name). It contains the following data:
supplier_id
supplier_name
10000
IBM
10001
Hewlett Packard
10002
Microsoft
10003
NVIDIA
We have a second table called orders with three fields (order_id, supplier_id, and order_date). It contains the following data:
order_id
supplier_id
order_date
500125
10000
2013/08/12
500126
10001
2013/08/13
500127
10004
2013/08/14
If we run the SQL statement (that contains a FULL OUTER JOIN) below:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
FULL OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Our result set would look like this:
supplier_id
supplier_name
order_date
10000
IBM
2013/08/12
10001
Hewlett Packard
2013/08/13
10002
Microsoft
<null>
10003
NVIDIA
<null>
<null>
<null>
2013/08/14
The rows for Microsoft and NVIDIA would be included because a FULL OUTER JOIN was used. However, you will notice that the order_date field for those records contains a <null> value.

The row for supplier_id 10004 would be also included because a FULL OUTER JOIN was used. However, you will notice that the supplier_id and supplier_name field for those records contain a <null> value.

No comments:

Post a Comment