The SQL OUTER JOIN clause is a variation of the SQL JOIN clause enables a SELECT statement to access more than one table. The JOIN clause controls how tables are linked. It is a qualifier of the SQL FROM clause.
The OUTER JOIN clause differs from the standard JOIN clause (also known as the INNER JOIN clause) in that rows are returned even when there are no matches through the JOIN critieria on the second table.
Use the SQL OUTER JOIN whenever multiple tables must be accessed through a SQL SELECT statement and results should be returned if there is not a match between the JOINed tables.
It can be useful when there is a need to merge data from two tables and to include all rows from both tables without depending on a match. Another use is to generate a large result set for testing purposes.
SQL OUTER JOIN is used as follows. The ON clause describes the conditions of the JOIN.
Important! A "cartesian product" can result if there is no relating the tables for the join. A row would be included for each combination between the two tables so if one table has 1,000 rows and the second table has 2,000 rows then 2,000,000 rows would be returned.
Important! If there are matches on the JOIN criteria then rows will still be returned. This is known an "OUTER JOIN". Use the "INNER JOIN" in cases where no rows should be returned when one side of the join is missing.
SQL OUTER JOIN Syntax
SQL OUTER JOIN Example
The following example JOINs the region and branch tables on the region_nbr column.
Here are the contents of the tables:
Table: REGION
region_nbr | region_name |
100 | East Region |
200 | Central Region |
300 | Virtual Region |
400 | West Region |
Table: BRANCH
branch_nbr | branch_name | region_nbr | employee_count |
108 | New York | 100 | 10 |
110 | Boston | 100 | 6 |
212 | Chicago | 200 | 5 |
404 | San Diego | 400 | 6 |
415 | San Jose | 400 | 3 |
This SQL Statement with OUTER JOIN is executed:
Here is the result. Note that the "Virtual Region" is included in the results even though it has no rows in the branch table. This is the difference between the INNER JOIN and OUTER JOIN.
region_nbr | region_name | branch_nbr | branch_name |
100 | East Region | 108 | New York |
100 | East Region | 110 | Boston |
200 | Central Region | 212 | Chicago |
300 | Virtual Region | NULL | NULL |
400 | West Region | 404 | San Diego |
400 | West Region | 415 | San Jose |
Advertisements:
Infogoal.com is organized to help you gain mastery.
Examples may be simplified to facilitate learning.
Content is reviewed for errors but is not warranted to be 100% correct.
In order to use this site, you must read and agree to the
terms of use, privacy policy and cookie policy.
Copyright 2006-2020 by Infogoal, LLC. All Rights Reserved.