SQL: Full Outer Join

Photo by Duy Pham on Unsplash

SQL: Full Outer Join

SQL (Structured Query Language) is a powerful tool that is commonly used for managing and analyzing large datasets. One of the most useful features of SQL is the ability to perform different types of joins, which allow you to combine data from multiple tables into a single dataset.

One type of join that is commonly used in SQL is the FULL OUTER JOIN. This type of join combines the rows from both tables, including those where there is no matching row in the other table. This can be useful when you need to include all of the data from both tables, regardless of whether there is a match.

To illustrate how to perform a FULL OUTER JOIN in SQL, let's consider the following example. Suppose we have two tables: one table contains information about customers, including their names and email addresses, while the other table contains information about orders, including the order ID, customer ID, and order date.

Here is an example of what these tables might look like:

sqlCopy codeCustomers Table:
+----+-------+-----------------------+
| id | name  | email                 |
+----+-------+-----------------------+
| 1  | John  | john@example.com      |
| 2  | Sarah | sarah@example.com     |
| 3  | David | david@example.com     |
| 4  | Lisa  | lisa@example.com      |
+----+-------+-----------------------+

Orders Table:
+----+------------+------------+
| id | customer_id| order_date |
+----+------------+------------+
| 1  | 2          | 2021-01-01 |
| 2  | 3          | 2021-02-02 |
| 3  | 1          | 2021-03-03 |
+----+------------+------------+

To perform a FULL OUTER JOIN on these tables, we can use the following SQL code:

sqlCopy codeSELECT *
FROM customers
FULL OUTER JOIN orders
ON customers.id = orders.customer_id;

In this code, we first select all columns from the "customers" table and join it with the "orders" table using a FULL OUTER JOIN. We specify the join condition using the "ON" keyword, which indicates that we want to join the tables on the "id" column in the "customers" table and the "customer_id" column in the "orders" table.

The result of this query will be a new table that combines all of the rows from both tables, including those where there is no matching row in the other table. Here is what the result would look like for our example:

sqlCopy code+----+-------+-----------------------+------+------------+------------+
| id | name  | email                 | id   | customer_id| order_date |
+----+-------+-----------------------+------+------------+------------+
| 1  | John  | john@example.com      | 3    | 1          | 2021-03-03 |
| 2  | Sarah | sarah@example.com     | 1    | 2          | 2021-01-01 |
| 3  | David | david@example.com     | 2    | 3          | 2021-02-02 |
| 4  | Lisa  | lisa@example.com      | NULL | NULL       | NULL       |
+----+-------+-----------------------+------+------------+------------+