SQL Joins
SQL Joins
Types of JOIN
Following are the types of JOIN that we can use in SQL:
Inner
Outer
Left
Right
SELECT column-name-list
FROM
table-name1 CROSS JOIN table-name2;
ID NAME
1 abhi
2 adam
4 alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
SELECT * FROM
class CROSS JOIN class_info;
The resultset table will look like,
ID NAME ID Address
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
As you can see, this join returns the cross product of all the records present in both the tables.
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 datatype present in both the tables to be joined.
The syntax for Natural Join is,
SELECT * FROM
table-name1 NATURAL JOIN table-name2;
ID NAME
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,
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
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
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
← Prev
Next →