SQL

SQL Server Joins

SQL Joins combine records from multiple tables:

The following tables are used to explain the concepts of joins

Product:

ProductIDProductNameColorPrice
1BicycleRed1000
2MotorbikeBlue10000
3CarGreen20000
4ComputerBlack20000

Orders:

OrderIDProductIDCustomerIDOrderQuantityUnitPriceDiscountTotal Amount
141120000200018000
22211000010009000

Employee:

EmpIDFirstnameLastnameTitleManagerID
888KevinBrownPresidentNull
889PeterHaynesGM888
890BenWilliamsSupervisor889
891JohnSmithClerk890

Inner Join: Returns common records from both the tables

SELECT p.ProductID,p.ProductName,o.OrderID
FROM Product p inner join Orders o on p.ProductID=o.ProductID

ProductIDProductNameOrderID
2Motorbike2
4Computer1

Left join: Returns all rows from the left table and matching rows from the right table
SELECT p.ProductID,p.ProductName,o.OrderID,o.ProductID
FROM Product p left join Orders o on p.ProductID=o.ProductID

ProductIDProductNameOrderIDProductID
1BicycleNullNull
2Motorbike22
3CarNullNull
4Computer14

 

Right join: Returns all rows from the right table and matching rows from the left table
SELECT p.ProductID,p.ProductName,o.OrderID,o.ProductID
FROM Product p right join Orders o on p.ProductID=o.ProductID

ProductIDProductNameOrderIDProductID
4Computer14
2Motorbike22

Full join: Returns all rows from both the tables
SELECT p.ProductID,p.ProductName,o.OrderID,o.ProductID
FROM Product p full join Orders o on p.ProductID=o.ProductID

ProductIDProductNameOrderIDProductID
1BicycleNullNull
2Motorbike22
3CarNullNull
4Computer14

Cross join: Returns the cartesian product
SELECT p.ProductID,p.ProductName,o.OrderID,o.ProductID
FROM Product p, Orders o

ProductIDProductNameOrderIDProductID
1Bicycle14
2Motorbike14
3Car14
4Computer14
1Bicycle22
2Motorbike22
3Car22
4Computer22

Self join: Joins the table to itself
SELECT
e1.Empid
,e1.FirstName
,e1.LastName
,e1.Title
,e2.FirstName as ManagerFirstName
,e2.LastName as ManagerLastName
FROM Employee e1, Employee] e2
Where e1.Managerid=e2.Empid

EmpIDFirstnameLastnameTitleManagerFirstNameManagerLastName
889PeterHaynesGMKevinBrown
890BenWilliamsSupervisorPeterHaynes
891JohnSmithClerkBenWilliams

As the President don’t have any manager, the record doesn’t show up. To show that record the following query can be used
SELECT Empid
,FirstName
,LastName
,Title
,Null as ManagerFirstName
,Null as ManagerLastName
FROM Employee
WHERE [Managerid] is null
Union
SELECT
e1.Empid
,e1.FirstName
,e1.LastName
,e1.Title
,e2.FirstName as ManagerFirstName
,e2.LastName as ManagerLastName
FROM Employee e1,Employee e2
Where e1.Managerid=e2.Empid

EmpIDFirstnameLastnameTitleManagerFirstNameManagerLastName
888KevinBrownPresidentNullNull
889PeterHaynesGMKevinBrown
891BenWilliamsSupervisorPeterHaynes
892JohnSmithClerkBenWilliams