OUTER
OUTER in SQL is a type of join used to combine rows from two or more tables, based on a related column between them. There are three types of OUTER join, namely LEFT OUTER join, RIGHT OUTER join and FULL OUTER join. Each serves to return a different subset of the combined data, based on the specified conditions. LEFT OUTER join returns all records from the left table and the matched records from the right table. RIGHT OUTER join returns all records from the right table and the matched records from the left table. FULL OUTER join returns all records when there is a match in either left or right table.
Example
Output
Explanation
The example depicts a LEFT JOIN (a type of OUTER JOIN) where all records from Customers
table and the matched records from Orders
table are returned. If there is no match, the result is NULL
from the right side (Orders
table), as demonstrated by the Sanchez
row. The ORDER BY
clause is used to sort the result-set in alphabetical order by CustomerName
.
Example
Output
Explanation
In this SQL statement, a LEFT JOIN
is used to combine rows from Customers
and Orders
tables based on a related column between them. For each customer_id
in Customers
, the query retrieves a corresponding order_id
from Orders
. If there is no matching order_id
for a customer_id
, the result is null
in the order_id
column.
Example
Output
Explanation
The FULL OUTER JOIN keyword returns all records when there is a match in the Orders (left) table or the Customers (right) table. The records from the Orders table are shown first. If there is no corresponding match in the Customers table, NULL is returned. The same applies for unmatched records in the Customers table when compared with the Orders table. The results are ordered by the OrderID.
Example
Output
Explanation
In the outer join SQL command example above:
- OrderID 1, 2, 3 are matched with John and Jane Doe, hence they display together.
- There is no customer matching OrderID 3, hence OrderID is displayed with NULL for CustomerName.
- Similarly, there is no order for Mike Doe, hence the NULL value for OrderID.
Example
Output
CustomerName | OrderID |
---|---|
Alfreds | 10308 |
Ana Trujillo | 10309 |
Antonio | 10310 |
Antonio | 10311 |
Around the Horn | NULL |
Explanation
In the example provided, the LEFT JOIN
operation is used to join Customers
and Orders
tables based on the common column CustomerID
. If a match is not found in the Orders
table, the output is NULL
. Thus, even customers who did not make any orders are included in the result set. The LIMIT 5
at the end of the query is used to restrict the output to the first five records.