Join in SQL
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as
single set of data. SQL Join is used for combining column from two or more tables
by using values common to both tables. Join Keyword is used in SQL queries for
joining two or more tables. Minimum required condition for joining table, is (n-
1) where n, is number of tables. A table can also join to itself known as, Self Join.
Types of Join
The following are the types of JOIN that we can use in SQL.
Inner
Outer
Left
Right
from table-name1
CROSS JOIN
table-name2;
Example of Cross JOIN
The class table,
ID NAME
1 abhi
2 adam
4 alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
from class,
1 abhi 1 DELHI
2 adam 1 DELHI
4 alex 1 DELHI
1 abhi 2 MUMBAI
2 adam 2 MUMBAI
4 alex 2 MUMBAI
1 abhi 3 CHENNAI
2 adam 3 CHENNAI
4 alex 3 CHENNAI
from table-name1
INNER JOIN
table-name2
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 2 MUMBAI
3 alex 3 CHENNAI
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and
same data type present in both the tables to be joined.
Natural Join Syntax is,
SELECT *
from table-name1
NATURAL JOIN
table-name2;
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME Address
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
In the above example, both the tables being joined have ID column(same name and
same datatype), hence the records for which value of ID matches in both the tables
will be the result of Natural Join of these two tables.
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide
further into,
from table-name1
table-name2
on table-name1.column-name = table-name2.column-name;
Left outer Join Syntax for Oracle is,
select column-name-list
from table-name1,
table-name2
on table-name1.column-name = table-name2.column-name(+);
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
from table-name1
table-name2
on table-name1.column-name = table-name2.column-name;
from table-name1,
table-name2
on table-name1.column-name(+) = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
from table-name1
table-name2
on table-name1.column-name = table-name2.column-name;
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
6 NOIDA
7 PANIPAT
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI