You are on page 1of 14

Joins

Joins
• Looked at many different joins types
• Inner and left joins are most common
• Only seen two table at once
• What about more than two tables?
• We can select from more than two tables
• Big advantage of using databases
• We just add another join keyword, then the
next table
• Select …. From table1
• Join table2 ON table1.col=table2.col
• JOIN table3 ON table2.col=table3.col

• Joined to table that had been added so far


• Join is used in both relational algebra and sql
• Relational algebra is mathematical notation
• But syntax is changed in SQL
joins
• Whenever we want to join two or more tables
to find the result which is not available in one
table.
• Lets say we have a employee table here:

Emp no Emp name address


1 Ali Multan
2 Usman Lhr
3 Ahmed Isb
4 Kashif Karachi
5 arif Sialkot
joins
• Suppose I need to find the address of a
employee whose name is Ali
• The only table that i require is employee table.
• I simply write the query
• Select address from employee where
Empname=‘Ali’;
• Output:
• multan
joins
• Lets say we have another table
dept no Dept name Emp no
D1 HR 1
D2 IT 2
D3 CS 3
D4 FINANCE 4
D5 ENGINEERING 5

Here emp no column act as foreign key and take


its reference from primary key of employee table.
Joins
• Lets say my question is :
• Find employee name of a employee who is
working in HR
• Now here we want help of both tables
employee and department.
• Whenever we need two or more tables we
must use of Joins.
joins
• We can only use join when we have a common
attribute between tables.
• In our above mentioned example we have a
“emp no” as common attribute.
• Join:
• Cross product + select statement(condition)
Types of Joins
• Cross join
• Natural join
• Conditional
• Equi join
• Self join
• Outer join
Natural Join
• Find the employee name who is working in a
deprtment
dept no Dept Emp no
name
D1 HR 1
D2 IT 2
D3 CS 3
D4 FINANCE 4
D5 ENGINEER 5
ING
Natural Join
• Select emp name FROM Emp,Dept WHERE
Emp.emp no=Dept.emp no

• OR
• SELECT emp name FROM Emp Natural Join
Dept;
Self Join
• When a table is joined to itself .

You might also like