OUTER JOIN

In SQL, joining tables is a common operation when it comes to retrieving data. One of the most frequently used types of joins is the OUTER JOIN. In this blog post, we will delve into the world of OUTER JOINs and explore the different types of JOINs that fall under this category.

Table of Contents

Introduction to OUTER JOIN

In SQL, the OUTER JOIN is used to combine rows from two or more tables based on a related column between them. The OUTER JOIN returns all rows from both tables, including unmatched rows.

There are three types of OUTER JOINs:

LEFT OUTER JOIN

A LEFT OUTER JOIN returns all rows from the left table, and the matched rows from the right table. If no match is found, NULL values are returned for the columns in the right table.

SELECT *
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id;

In the above example, the LEFT OUTER JOIN returns all rows from “table1” and the matching rows from “table2” based on the “id” column. If no matching row is found in “table2”, the corresponding columns from “table2” will have NULL values.

RIGHT OUTER JOIN

A RIGHT OUTER JOIN returns all rows from the right table, and the matched rows from the left table. If no match is found, NULL values are returned for the columns in the left table.

SELECT *
FROM table1
RIGHT OUTER JOIN table2
ON table1.id = table2.id;

In the above example, the RIGHT OUTER JOIN returns all rows from “table2” and the matching rows from “table1” based on the “id” column. If no matching row is found in “table1”, the corresponding columns from “table1” will have NULL values.

FULL OUTER JOIN

A FULL OUTER JOIN returns all rows from both tables, regardless of whether there is a match or not. If no match is found, NULL values are returned for columns in the opposite table.

SELECT *
FROM table1
FULL OUTER JOIN table2
ON table1.id = table2.id;

In the above example, the FULL OUTER JOIN returns all rows from both “table1” and “table2” based on the “id” column. If no matching row is found in either table, the corresponding columns from the opposite table will have NULL values.

Conclusion

In this blog post, we explored the different types of OUTER JOINs in SQL. We learned about the LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN, and how they differ in terms of the rows they return and the NULL values they produce. Understanding these join types is essential when it comes to manipulating and combining data from multiple tables.

#sql #join #outer