AdBlock Detected!
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.
SQL Outer Join |
|
SQL > SQL JOIN >
Outer Join
Previously, we had looked at left join, or inner join, where we select rows common to the participating tables to a join. What about the cases where we are interested in selecting elements in a table regardless of whether they are present in the second table? We will now need to use the SQL OUTER JOIN command. An SQL OUTER JOIN returns all rows from one table plus matching rows from the second table — rows with no match get NULL in the columns from the second table. This is useful when you need a complete list from one table even if some entries have no corresponding data in the other.
The syntax for performing an outer join in SQL is database-dependent. For example, in Oracle, we will place an "(+)" in the WHERE clause on the other side of the table for which we want to include all the rows. Let's assume that we have the following two tables, Table Store_Information
Table Geography
and we want to find out the sales amount for all of the stores. If we do a regular join, we will not be able to get what we want because we will have missed "New York," since it does not appear in the Store_Information table. Therefore, we need to perform an outer join on the two tables above:
Note that in this case, we are using the Oracle syntax for outer join. Result:
Note: NULL is returned when there is no match on the second table. In this case, "New York" does not appear in the table Store_Information, thus its corresponding "SALES" column is NULL. Frequently Asked QuestionsShould I use the Oracle (+) syntax or standard LEFT OUTER JOIN syntax?For new code, always prefer the ANSI standard syntax: LEFT OUTER JOIN ... ON .... It is portable across all major databases (MySQL, PostgreSQL, SQL Server, Oracle) and is easier to read and maintain. The Oracle (+) syntax is legacy and only works in Oracle. What is a FULL OUTER JOIN?A FULL OUTER JOIN returns all rows from both tables. Where there is no match on either side, NULL is returned for the missing columns. This is useful when you want to see all data from both tables side by side, regardless of matching keys. Can I use WHERE conditions with an OUTER JOIN?Yes, but be careful: placing a filter condition on the optional (outer) table's column in a WHERE clause can accidentally convert an outer join into an inner join, because NULL rows will not satisfy the condition. Put such filters in the ON clause of a LEFT/RIGHT JOIN instead. What is the difference between outer join and cross join?A cross join returns the Cartesian product — every combination of rows from both tables — with no matching condition. An outer join uses a condition (like ON or WHERE) to match rows, and includes unmatched rows with NULLs from the optional table.
|
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.