Overview
The Join in SQL is used to combine rows from two or more tables based on common fields. There are various type of join (inner, left, right …). The common fields are always specified in on clause statement. The “on" clause is often messed up with “where" clause. Also, the are various name of same join type which make us confused.
Inner Join
Syntax: Select * from table1 inner [optional] join table2 on table1.key = table2.key.
In Oracle, Inner is optional for Inner Join.
Left Join
Syntax: Select * from table1 left join table2 on table1.key = table2.key
In Oracle, Outer is optional for Left/Right Join
Equivalent Syntax
A LEFT JOIN B |
A LEFT OUTER JOIN B |
A RIGHT JOIN B |
A RIGHT OUTER JOIN B |
A FULL JOIN B |
A FULL OUTER JOIN B |
A INNER JOIN B |
A JOIN B |
The Difference Between Where Clause and On Clause
On Clause is used to filter join table row
Where Clause is used to filter result row
Example
Inner Join
Select table1.id as Table1ID, table1.name as Table1Name, table2.id as Table2ID, table2.name as Table2Name from table1 join table2 on table1.id = table.id
Table1ID |
Table1Name |
Table2ID |
Table2Name |
1 |
Table 1 Item 1 |
1 |
Table 2 Item2 |
2 |
Table 1 Item 2 |
2 |
Table 2 Item 3 |
3 |
Table 1 Item 3 |
3 |
Table 2 Item 3 |
Left Join
Select table1.id as Table1ID, table1.name as Table1Name, table2.id as Table2ID, table2.name as Table2Name from table1 left join table2 on table1.id = table.id
Table1ID |
Table1Name |
Table2ID |
Table2Name |
1 |
Table 1 Item 1 |
1 |
Table 2 Item 2 |
2 |
Table 1 Item 2 |
2 |
Table 2 Item 3 |
3 |
Table 1 Item 3 |
3 |
Table 2 Item 3 |
Left Join On <Con1> And <Con2>
Select table1.id as Table1ID, table1.name as Table1Name, table2.id as Table2ID, table2.name as Table2Name from table1 left join table2 on table1.id = table.id and table1.id=1
Table1ID |
Table1Name |
Table2ID |
Table2Name |
1 |
Table 1 Item 1 |
1 |
Table 2 Item 2 |
2 |
Table 1 Item 2 |
(null) |
(null) |
3 |
Table 1 Item 3 |
(null) |
(null) |
Left Join On <Con1> Where <Con2>
Select table1.id as Table1ID, table1.name as Table1Name, table2.id as Table2ID, table2.name as Table2Name from table1 left join table2 on table1.id = table.id where table1.id=1
Table1ID |
Table1Name |
Table2ID |
Table2Name |
1 |
Table1 Item 1 |
1 |
Table 2 Item 2 |
Conclusion
In Short, The On Clause and Where Clause in Inner Join are equivalent. But for Left join, they are different.
Visual Representation of Various Join
From: http://stackoverflow.com/questions/15891863/what-is-the-difference-between-join-keyword-and-inner-join-keyword-in-oracle-sql
Reference:
http://www.w3schools.com/sql/sql_join.asp
http://stackoverflow.com/questions/565620/difference-between-join-and-inner-join
http://stackoverflow.com/questions/406294/left-join-and-left-outer-join-in-sql-server