Outer joins can be a left, a right, or full outer join.
Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:
LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. [Source]
SQL LEFT JOIN Example
The "Consumers" table:
P_Id | LastName | FirstName | Address | City |
---|---|---|---|---|
1 | Kumar | Ram | Delhi | AAA |
2 | Singh | Laxman | Chandigarh | AAA |
3 | Sharma | Sameer | Ambala | BBB |
The "Orders" table:
O_Id | OrderNo | P_Id |
---|---|---|
1 | 77895 | 3 |
2 | 44678 | 3 |
3 | 22456 | 1 |
4 | 24562 | 1 |
5 | 34764 | 15 |
Now we want to list all the Consumers and their orders - if any, from the tables above.
We use the following SELECT statement:
SELECT Consumers.LastName, Consumers.FirstName, Orders.OrderNo
FROM Consumers
LEFT JOIN Orders
ON Consumers.P_Id=Orders.P_Id
ORDER BY Consumers.LastName
The result-set will look like this:
LastName | FirstName | OrderNo |
---|---|---|
Kumar | Ram | 22456 |
Kumar | Ram | 24562 |
Sharma | Sameer | 77895 |
Sharma | Sameer | 44678 |
Singh | Laxman |
The LEFT JOIN keyword returns all the rows from the left table (Consumers), even if there are no matches in the right table (Orders).
RIGHT JOIN or RIGHT OUTER JOIN
A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.
FULL JOIN or FULL OUTER JOIN
A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
Why to use outer joins
Use left or right outer joins when you require a complete list of data that is
stored in one of the joined tables in addition to the information that matches the join condition.
When to use outer joins
Use an outer join when you want to find unmatched rows. (because either you want to find missing values from one of the tables, like in this case, or you may want to include all values from your tables even if they are missing values in the other table).
No comments:
Post a Comment