0% found this document useful (0 votes)
25 views

SQL Join

Uploaded by

Meaw Cat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

SQL Join

Uploaded by

Meaw Cat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

SQL JOIN

SQL Join is used to fetch data from two or more tables, which is joined to appear as
single set of data. It 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, which is known as, Self Join.

Types of JOIN
Following are the types of JOIN that we can use in SQL:

 Inner

 Outer

 Left

 Right

Cross JOIN or Cartesian Product


This type of JOIN returns the cartesian product of rows from the tables in Join. It will
return a table which consists of records which combines each row from the first table
with each row of the second table.
Cross JOIN Syntax is,
SELECT column-name-list

FROM

table-name1 CROSS JOIN table-name2;

Example of Cross JOIN


Following is the class table,
ID NAME

1 abhi

2 Adam

4 Alex

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

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Cross JOIN query will be,

SELECT * FROM

class CROSS JOIN class_info;

The resultset table will look like,


As you can see, this join returns the cross product of all the records present in both the
tables.

INNER Join or EQUI Join


This is a simple JOIN in which the result is based on matched data as per the equality
condition specified in the SQL query.
Inner Join Syntax is,
SELECT column-name-list FROM

table-name1 INNER JOIN table-name2


WHERE table-name1.column-name = table-name2.column-name;

Example of INNER JOIN


Consider a class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Inner JOIN query will be,


SELECT * from class INNER JOIN class_info where class.id = class_info.id;
The resultset table will look like,

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;

Example of Natural JOIN


Here is the class table,

ID NAME

1 abhi

2 adam
3 alex

4 anu

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Natural join query will be,


SELECT * from class NATURAL JOIN class_info;

The resultset table will look like,

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,

1. Left Outer Join

2. Right Outer Join

3. Full Outer Join

LEFT Outer Join


The left outer join returns a resultset table with the matched data from the two tables
and then the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,
SELECT column-name-list FROM

table-name1 LEFT OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;

To specify a condition, we use the ON keyword with Outer Join.


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(+);
Example of Left Outer Join
Here is the class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA
8 PANIPAT

Left Outer Join query will be,


SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id = class_info.id);

The resultset table will look like,

ID NAME ID Address

1 Abhi 1 DELHI

2 Adam 2 MUMBAI

3 Alex 3 CHENNAI

4 Anu null null

5 Ashish null null

RIGHT Outer Join


The right outer join returns a resultset table with the matched data from the two tables
being joined, then the remaining rows of the right table and null for the
remaining left table's columns.
Syntax for Right Outer Join is,
SELECT column-name-list FROM

table-name1 RIGHT OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;

Right outer Join Syntax for Oracle is,


SELECT column-name-list FROM

table-name1, table-name2

ON table-name1.column-name(+) = table-name2.column-name;

Example of Right Outer Join


Once again the class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

and the class_info table,

ID Address
1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Right Outer Join query will be,


SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);

The resultant table will look like,

ID NAME ID Address

1 Abhi 1 DELHI

2 Adam 2 MUMBAI

3 Alex 3 CHENNAI

null Null 7 NOIDA

null Null 8 PANIPAT


Full Outer Join
The full outer join returns a resultset table with the matched data of two table then
remaining rows of both left table and then the right table.
Syntax of Full Outer Join is,
SELECT column-name-list FROM

table-name1 FULL OUTER JOIN table-name2

ON table-name1.column-name = table-name2.column-name;

Example of Full outer join is,


The class table,

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 Ashish

and the class_info table,
ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Full Outer Join query will be like,


SELECT * FROM class FULL OUTER JOIN class_info ON (class.id = class_info.id);

The resultset table will look like,

ID NAME ID Address

1 Abhi 1 DELHI

2 Adam 2 MUMBAI

3 Alex 3 CHENNAI

4 Anu null null


5 Ashish null null

null Null 7 NOIDA

null Null 8 PANIPAT

DBMS - Joins
Advertisements

 Previous Page
Next Page  
We understand the benefits of taking a Cartesian product of two relations, which gives
us all the possible tuples that are paired together. But it might not be feasible for us in
certain cases to take a Cartesian product where we encounter huge relations with
thousands of tuples having a considerable large number of attributes.
Join is a combination of a Cartesian product followed by a selection process. A Join
operation pairs two tuples from different relations, if and only if a given join condition is
satisfied.
We will briefly describe various join types in the following sections.

Theta (θ) Join


Theta join combines tuples from different relations provided they satisfy the theta
condition. The join condition is denoted by the symbol θ.

Notation

R1 ⋈θ R2
R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that
the attributes don’t have anything in common, that is R1 ∩ R2 = Φ.
Theta join can use all kinds of comparison operators.

Student

SID Name Std

101 Alex 10

102 Maria 11

Subjects

Class Subject

10 Math

10 English

11 Music

11 Sports

Student_Detail −
STUDENT ⋈Student.Std = Subject.Class SUBJECT
Student_detail

SID Name Std Class Subject

101 Alex 10 10 Math


101 Alex 10 10 English

102 Maria 11 11 Music

102 Maria 11 11 Sports

Equijoin
When Theta join uses only equality comparison operator, it is said to be equijoin. The
above example corresponds to equijoin.

Natural Join (⋈)


Natural join does not use any comparison operator. It does not concatenate the way a
Cartesian product does. We can perform a Natural Join only if there is at least one
common attribute that exists between two relations. In addition, the attributes must
have the same name and domain.
Natural join acts on those matching attributes where the values of attributes in both the
relations are same.

Courses

CID Course Dept

CS01 Database CS

ME01 Mechanics ME

EE01 Electronics EE

HoD

Dept Head
CS Alex

ME Maya

EE Mira

Courses ⋈ HoD

Dept CID Course Head

CS CS01 Database Alex

ME ME01 Mechanics Maya

EE EE01 Electronics Mira

Outer Joins
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only
those tuples with matching attributes and the rest are discarded in the resulting
relation. Therefore, we need to use outer joins to include all the tuples from the
participating relations in the resulting relation. There are three kinds of outer joins − left
outer join, right outer join, and full outer join.

Left Outer Join(R   S)


All the tuples from the Left relation, R, are included in the resulting relation. If there are
tuples in R without any matching tuple in the Right relation S, then the S-attributes of
the resulting relation are made NULL.

Left

A B
100 Database

101 Mechanics

102 Electronics

Right

A B

100 Alex

102 Maya

104 Mira

Courses   HoD

A B C D

100 Database 100 Alex

101 Mechanics --- ---

102 Electronics 102 Maya

Right Outer Join: ( R   S )


All the tuples from the Right relation, S, are included in the resulting relation. If there
are tuples in S without any matching tuple in R, then the R-attributes of resulting
relation are made NULL.
Courses   HoD

A B C D

100 Database 100 Alex

102 Electronics 102 Maya

--- --- 104 Mira

Full Outer Join: ( R   S)


All the tuples from both participating relations are included in the resulting relation. If
there are no matching tuples for both relations, their respective unmatched attributes
are made NULL.

Courses   HoD

A B C D

100 Database 100 Alex

101 Mechanics --- ---

102 Electronics 102 Maya

--- --- 104 Mira

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
 (INNER) JOIN: Returns records that have matching values in both
tables
 LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
 FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table

       

oining three or more tables in SQL


There may occur some situations sometimes where data needs to be fetched from
three or more tables. This article deals with two approaches to achieve it.
Example:
Creating three tables:
1. student
2. marks
3. details
Note: Click on image if not clear to view in bigger size.
Table 1: student
create table student(s_id int primary key,
s_name varchar(20));

insert into student values(1, 'Jack');


insert into student values(2, 'Rithvik');
insert into student values(3, 'Jaspreet');
insert into student values(4, 'Praveen');
insert into student values(5, 'Bisa');
insert into student values(6, 'Suraj');

Table 2: marks
create table marks(school_id int primary key, s_id int,
score int, status varchar(20));

insert into marks values(1004, 1, 23, 'fail');


insert into marks values(1008, 6, 95, 'pass');
insert into marks values(1012, 2, 97, 'pass');
insert into marks values(1016, 7, 67, 'pass');
insert into marks values(1020, 3, 100, 'pass');
insert into marks values(1025, 8, 73, 'pass');
insert into marks values(1030, 4, 88, 'pass');
insert into marks values(1035, 9, 13, 'fail');
insert into marks values(1040, 5, 16, 'fail');
insert into marks values(1050, 10, 53, 'pass');

Table 3: details
create table details(address_city varchar(20), email_ID varchar(20),
school_id int, accomplishments varchar(50));

insert into details values('Banglore', '[email protected]',


1020, 'ACM ICPC selected');
insert into details values('Hyderabad', '[email protected]',
1030, 'Geek of the month');
insert into details values('Delhi', '[email protected]',
1012, 'IOI finalist');
insert into details values('Chennai', '[email protected]',
1111, 'Geek of the year');
insert into details values('Banglore', ' [email protected]',
1008, 'IMO finalist');
insert into details values('Mumbai', '[email protected]',
2211, 'Made a robot');
insert into details values('Ahmedabad', '[email protected]',
1172, 'Code Jam finalist');
insert into details values('Jaipur', '[email protected]',
1972, 'KVPY finalist');
Two approaches to join three or more tables:
1. Using joins in sql to join the table:
The same logic is applied which is done to join 2 tables i.e. minimum number of join
statements to join n tables are (n-1).
Query:
select s_name, score, status, address_city, email_id,
accomplishments from student s inner join marks m on
s.s_id = m.s_id inner join details d on
d.school_id = m.school_id;
Output:

2. Using parent-child relationship:
This is rather an interesting approach. Create column X as primary key in one table and
as foreign key in another table (i.e creating a parent-child relationship).
Let’s look in the tables created:
s_id is the primary key in student table and is foreign key in marks table. (student
(parent) – marks(child)).
school_id is the primary key in marks table and foreign key in details
table. (marks(parent) – details(child)).
Query:
select s_name, score, status, address_city,
email_id, accomplishments from student s,
marks m, details d where s.s_id = m.s_id and
m.school_id = d.school_id;
Output:

You might also like