You are on page 1of 19

Sql JOINS and the Sql Server Management Studio Query Designer

There are a whole bunch of articles, blog entries and tutorials that seek to explain how SQL JOINS work. Some of them are excellent, and others are just confusing. The reason I am adding my go at trying to clarify JOINS to the mix is to highlight how proper use of the tools available to you can seriously reduce the chances of getting the JOIN syntax or type wrong. Since JOINS are all about how to relate data from one table to another, I thought it appropriate to illustrate the subject using Parents and Children (who may, or may not be related to eachother). So let's meet the families. Peter has 2 children: Jo and Roger Mary has 1 child: Susan Alice has 2 children: Kevin and Rachel John has 1 child: David Jimmy has no children. Sam and Ian have no parents. They are orphans. This is how they appear in database tables: Parents and Children. Children are related to Parents by the AdultID.

INNER JOIN - All parents with children


If we open up the Query Designer in Sql Server Management Studio, and add the 2 tables, they are joined on the AdultID by default using an INNER JOIN. If they are not automatically joined (by the line that appears between the tables) you have not set AdutlID in the Children table as a

foreign key. However, you can simply drag AdultID in the Children table, and drop it onto the AdultID in the Parents table to create the relationship.

Selecting AdultName and ChildName in the repsective columns generates the following SQL:

And when the SQL is executed, all parents with children are returned:

So who's missing? Batchelor Jimmy is nowhere to be seen (because he has no children) and nor are our orphans, Sam and Ian. INNER JOIN only returns rows from the two tables where there are matches based on the JOIN-predicate, which in this case is where Parents.AdultID has a matching record in Children.AdultID.

LEFT OUTER JOIN - All Parents, and their children if they have any
Right-clicking on the diamond in the middle of the Join line in the query designer reveals a context menu with some options for the JOIN. If we select "Select All Rows from Parents", the left hand side of the diamond fills out, and some new SQL is generated:

When this is executed, the LEFT OUTER JOIN returns all the parents (including Jimmy), irrespective of whether they have children or not:

It also returns all the children that have parents. In the case of Jimmy, he has NULL against the ChildName column, because he has no children.

RIGHT OUTER JOIN - All children, and their parents if they have any
We deselect "Select All Rows from Parents", and select "Select All Rows from Children" instead. The right hand side (or perhaps the RIGHT OUTER side?)of the diamond is now filled out, and the SQL changes to reflect this:

When executed, our orphans appear in the ChildName column, with NULL against the parent column. Jimmy is nowhere to be seen. I think he just hates kids.

FULL OUTER JOIN - All Parents and all children


Selecting both options from the JOIN property menu gives us a FULL OUTER JOIN:

This returns all records from both sides of the relationship, regardless of whether there are matching records:

CROSS JOIN - Cartesian product


If we remove the JOIN line:

we get a CROSS JOIN, which results, when executed, in the Cartesian product of both tables - 5 parents x 8 children = 40 rows. That means that every row in one table is matched to every row in the other table:

Notice the absence of a JOIN-predicate. There are some obscure uses for CROSS JOINS, including the creation of test data, but generally, they are not used.

Using JOINS to Find Unmatched records


If you study the results of, for example, the LEFT OUTER JOIN, you will notice that Jimmy was returned with a value of NULL in the Children table side of the resultset. Applying this as a filter to a JOIN query is very useful to finding records in one table that have no related records in the second table.

If we type "IS NULL" in the Filter column against the AdultID column of the Children table to the LEFT OUTER JOIN example, we end up with the following diagram and SQL:

and executing this results in Jimmy being returned on his own as the only record in the Parents table that doesn't have a matching record in the Children table:

Conversely, doing the same thing to the AdultID in the Adults table in the RIGHT OUTER JOIN example:

leads to this SQL and diagram:

which when executed results in both Orphans being returned, because again, they have no matching record in the Parents table:

From the questions posted to newsgroups and forums, it seems to me that plenty of people are either unaware of the existence of the Query Designer, or don't use it because they consider it some kind of cheating. For the former group, hopefully this article will show you something new. For the latter group, there is nothing wrong with using the tools available to you. It speeds up development and reduces your chance of errors.

Joins in sql server, Inner Join,Cross Join,Left Outer Join,Equi join, Right Outer Join, Full Outer Join
By: Suresh Dasari Dec 10, 2011 Categories: General , SQL Joins , SQL Server Introduction: In this post I will explain what are the Joins in SQL Server and different types of Joins example (SQL LEFT outer Join, SQL RIGHT outer Join, SQL FULL outer Join, SQL Cross Join, SQL inner Join sample, Self Join example) and uses of Joins in SQL Server. Description: In SQL joins are used to get data from two or more tables based on relationship between some of the columns in tables. In most of the cases we will use primary key of first table and foreign key of secondary table to get data from tables by using this relationship we can reduce the duplication of data in every table. Before enter into Joins concept first design two tables in database and enter data like as shown below Create one table with primary key and give name as UserDetails UserID 1 2 3 Here UserID is UserName FirstName LastName Dasari Donthi Dasari

SureshDasari Suresh PrasanthiDonthi Prasanthi MaheshDasari Mahesh the Primary key in UserDetails table

After that create another table with Foreign Key and give name as OrderDetails OrderID 1 2 3 OrderNo 543224 213424 977776 UserID 1 2 3

4 323233 3 5 998756 1 Here OrderID is the Primary key and UserID is the foreign key in OrderDetails table. SQL contains different types of Joins we will see each concept with example by using above tables. Types of Joins 1) Inner Joins 2) Outer Joins 3) Self Join Inner Join The join that displays only the rows that have a match in both the joined tables is known as inner join. This is default join in the query and view Designer.

SELECT t1.column_name,t2.column_name FROM table_name1 t1 INNER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for inner join Example SELECT u.UserName,u.LastName,o.OrderNo FROM UserDetails u INNER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserName LastName OrderNo SureshDasari Dasari 543224 PrasanthiDonthi Donthi 213424 MaheshDasari Dasari 977776 MaheshDasari Dasari 323233 SureshDasari Dasari 998756 We can write our inner join query like this also it will give same result SELECT u.UserName,u.LastName,o.OrderNo FROM UserDetails u JOIN OrderDetails o ON u.UserID=o.UserID Based on above result we can say that INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in "UserDetails" that do not have matches in "OrderDetails", those rows will NOT be listed.

In inner Join we are having different types of Joins those are 2 1) Equi Join 2) Natural Join 3) Cross Join Equi Join The Equi join is used to display all the matched records from the joined tables and also display redundant values. In this join we need to use * sign to join the table.

SELECT * FROM table_name1 t1 INNER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Equi join Example SELECT * FROM UserDetails u INNER JOIN OrderDetails o ON u.UserID=o.UserID Once we run above query our output will be like this UserID UserName FirstName LastName OrderID OrderNo UserID 1 SureshDasari Suresh Dasari 1 543224 1 2 PrasanthiDonthi Prasanthi Donthi 2 213424 2 3 MaheshDasari Mahesh Dasari 3 977776 3 3 MaheshDasari Mahesh Dasari 4 323233 3 1 SureshDasari Suresh Dasari 5 998756 1 In equi join we need to use only equality comparisons in the join relation. If we use other operators such as (<,>) for our comparison condition then our Joins disqualifies for equi join. Natural Joins The Natural join is same as our Equi join but only the difference is it will restrict to display redundant values. Syntax for Natural Join SELECT * FROM table_name1 t1 NATURAL JOIN table_name2 t2 Example SELECT * FROM UserDetails NATURAL JOIN OrderDetails

Note: These NATURAL Joins wont work in our SQL Server (only supports in Oracle) it will throw syntax error. If you observe above code "NATURAL" is not highlighted, indicating that it is not recognized as a keyword. Cross Join A cross join that produces Cartesian product of the tables that involved in the join. The size of a Cartesian product is the number of the rows in first table multiplied by the number of rows in the second table. Syntax for Cross Join SELECT * FROM table_name1 CROSS JOIN table_name2 Or we can write it in another way also SELECT * FROM table_name1,table_name2 Now check the below query for Cross join Example SELECT * FROM UserDetails CROSS JOIN OrderDetails Or SELECT * FROM UserDetails, OrderDetails Once we run that query our output will be like this UserID 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 UserName SureshDasari SureshDasari SureshDasari SureshDasari SureshDasari PrasanthiDonthi PrasanthiDonthi PrasanthiDonthi PrasanthiDonthi PrasanthiDonthi MaheshDasari MaheshDasari MaheshDasari MaheshDasari MaheshDasari FirstName Suresh Suresh Suresh Suresh Suresh Prasanthi Prasanthi Prasanthi Prasanthi Prasanthi Mahesh Mahesh Mahesh Mahesh Mahesh LastName Dasari Dasari Dasari Dasari Dasari Donthi Donthi Donthi Donthi Donthi Dasari Dasari Dasari Dasari Dasari OrderID 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 OrderNo 543224 213424 977776 323233 998756 543224 213424 977776 323233 998756 543224 213424 977776 323233 998756 UserID 1 2 3 3 1 1 2 3 3 1 1 2 3 3 1

Outer Joins

A join that return all the rows that satisfy the condition and unmatched rows in the joined table is an Outer Join. We are having three types of Outer Joins Left Outer Join Right Outer Join Full Outer Join Left Outer Join The left outer join displays all the rows from the first table and matched rows from the second table. Syntax for Left Outer Join SELECT Column_List FROM table_name1 t1 LEFT OUTER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Left Outer join Example SELECT u.UserID,u.UserName,o.OrderNo FROM UserDetails u LEFT OUTER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserID 1 1 2 3 3 Right Outer Join The right outer join displays all the rows from the second table and matched rows from the first table. Syntax for Right Outer Join SELECT Column_List FROM table_name1 t1 RIGHT OUTER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Right Outer join Example UserName SureshDasari SureshDasari PrasanthiDonthi MaheshDasari MaheshDasari OrderNo 543224 998756 213424 977776 323233

SELECT u.UserID,u.UserName,o.OrderNo FROM UserDetails u RIGHT OUTER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserID 1 2 3 3 1 Full Outer Join Full Outer Join displays all the matching and non matching rows of both the tables. Syntax for Full Outer Join SELECT Column_List FROM table_name1 t1 FULL OUTER JOIN table_name2 t2 ON t1.column_name=t2.column_name Now check the below query for Full Outer join Example SELECT u.UserID,u.UserName,o.OrderNo FROM UserDetails u FULL OUTER JOIN OrderDetails o ON u.UserID=o.UserID Once we run that query our output will be like this UserID 1 1 2 3 3 Self Join Joining the table itself called self join. Self join is used to retrieve the records having some relation or similarity with other records in the same table. Here we need to use aliases for the same table to set a self join between single table and retrieve records satisfying the condition in where clause. To implement self join first design table and give a name as EmployeeDetails UserName SureshDasari SureshDasari PrasanthiDonthi MaheshDasari MaheshDasari FirstName Suresh Suresh Prasanthi Mahesh Mahesh LastName Dasari Dasari Donthi Dasari Dasari OrderID 1 5 2 3 4 OrderNo 543224 998756 213424 977776 323233 UserID 1 1 2 3 3 UserName SureshDasari PrasanthiDonthi MaheshDasari MaheshDasari SureshDasari OrderNo 543224 213424 977776 323233 998756

EmpID 1 2 3 4 5 6 7

EmpName Suresh Prasanthi Mahesh Sai Nagaraju Mahendra Sanjay

EmpMgrID 2 4 2 1 1 3 3

Now I want to get manager names of particular employee for that we need to write query like this select e2.EmpName,e1.EmpName as 'Manager' from EmployeeDetails e1 INNER JOIN EmployeeDetails e2 on e1.EmpID=e2.EmpMgrID Here if you observe above query EmployeeDetails table joined itself using table aliases e1 and e2. After that run our query output will be like this EmpName Sai Nagaraju Suresh Mahesh Mahendra Sanjay Prasanthi Manger Suresh Suresh Prasanthi Prasanthi Mahesh Mahesh Sai

SQL Joins
By Vivek Johari, 20 Aug 2010 4.68 (24 votes)

I generally feel that people are afraid of Joins in SQL Server. But if they know what the different types of Joins in SQL Server are and how they can be best used then they really enjoy using them. By using the joins we can get data from many tables based on some logical conditions.

The Different Types of Joins in SQL Server


1. Inner join or Equi join

2. 3.

Outer Join Cross join Let's suppose we have two tables Employee and Department whose description is given below:Collapse | Copy Code

CREATE TABLE [dbo]. [Employee]( [Empid] [Int] IDENTITY (1, 1) NOT NULL Primary key, [EmpNumber] [nvarchar](50) NOT NULL, [EmpFirstName] [nvarchar](150) NOT NULL, [EmpLastName] [nvarchar](150) NULL, [EmpEmail] [nvarchar](150) NULL, [Managerid] [int] NULL, [Departmentid] [INT] ) CREATE TABLE [dbo].[Department]( [Departmenttid] [int] IDENTITY (1, 1) NOT NULL primary key, [DepartmentName] [nvarchar](255) NOT NULL )

After the creation of the tables we need to insert the data into these tables. To insert the data the following queries are used:Collapse | Copy Code

insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A001','Samir','Singh','samir@abc.com',2,2) insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A002','Amit','Kumar','amit@abc.com',1,1) insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A003','Neha','Sharma','neha@abc.com',1,2) insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A004','Vivek','Kumar','vivek@abc.com',1,NULL) insert into Department(DepartmentName) values('Accounts') insert into Department(DepartmentName) values('Admin') insert into Department(DepartmentName) values('HR') insert into Department(DepartmentName) values('Technology')

Inner Join
This type of join is also known as the Equi join. This join returns all the rows from both tables where there is a match. This type of join can be used in the situation where we need to select only those rows which have values common in the columns which are specified in the ON clause.

Now, if we want to get employee id, employee first name, employee's last name and their department name for those entries employee which belongs to at least one department, then we can use the inner join.

Query for Inner Join


Collapse | Copy Code

SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp INNER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid

Result
Collapse | Copy Code

Empid 1 2 3

EmpFirstName Samir Amit Neha

EmpLastName Singh Kumar Sharma

DepartmentName Admin Accounts Admin

Explanation
In this query, we used the inner join based on the column "Departmentid" which is common in both the tables "Employee" and "Department". This query will give all the rows from both the tables which have common values in the column "Departmentid". Neha Sharma and Samir Singh has the value "2" in the Departmentid column of the table Employee. In the Department table, the Department "Admin" has the value "2" in the Departmentid column. Therefore the above query returns two rows for the department "Admin", one for Neha Sharma and another for Samir Singh.

Self Join
Sometime we need to join a table to itself. This type of join is called Self join. It is one of the type of inner join where both the columns belong to the same table. In this Join, we need to open two copies of a same table in the memory. Since the table name is the same for both instances, we use the table aliases to make identical copies of the same table to be open in different memory locations. For example if we need to get the employee name and their manager name we need to use the self join, since the managerid for an employee is also stored in the same table as the employee.

Query for the Self Join


Collapse | Copy Code

SELECT Emp1.Empid, Emp1.EmpFirstName+' '+Emp1.EmpLastName as EmployeeName, Emp2.EmpFirstName+' '+Emp2.EmpLastName as ManagerName FROM Employee Emp1 INNER JOIN Employee Emp2

ON Emp1.Managerid=Emp2.Empid

Result
Collapse | Copy Code

Empid 1 2 3 4

EmployeeName Samir Singh Amit Kumar Neha Sharma Vivek Kumar

ManagerName Amit Kumar Samir Singh Samir Singh Samir Singh

Explanation
Since the employee and the manager information is contained in the same table (Employee, since both are employees), we have to use the Self Join. In the self join query, we make two copies of the table Employee by using the aliases Emp1 and Emp2 and then use Inner join between them by using the managerid column of the Emp1 and Empid column of the table Emp2.In this example, we use managerid and empid columns of the Employee table since the employee id of the manager of an employee is stored in the managerid of the Employee table.

Outer Join
This type of join is needed when we need to select all the rows from the table on the left (or right or both) regardless of whether the other table has common values or not and it usually enter null values for the data which is missing. The Outer join can be of three types 1. 2. 3. Left Outer Join Right Outer Join Full Outer Join

Left Outer Join


If we want to get employee id, employee first name, employes last name and their department name for all the employees regardless of whether they belong to any department or not,then we can use the left outer join. In this case we keep the Employee table on the left side of the join clause. It will insert NULL values for the data which is missing in the right table.

Query for Left Outer Join


Collapse | Copy Code

SELECT Emp.Empid, Emp.EmpFirstName,

Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp LEFT OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid

Result
Collapse | Copy Code

Empid 1 2 3 4

EmpFirstName Samir Amit Neha Vivek

EmpLastName Singh Kumar Sharma Kumar

DepartmentName Admin Accounts Admin NULL

Explanation
Since we have use the Left Outer Join, this query will give the information (Employee id, Employee first name, Employee last name and their department name) for all the employee from the Employee table and it insert NULL value in the DepartmentName column where the employee does not belong to any department. In the table Employee, since Samir Singh, Amit Kumar and Neha Sharma have values in their Departmentid column, therefore the above query will display their Department name under the heading DepartmentName.But since Vivek Kumar doesn't belongs to any department and has null value in the column Departmentid therefore the above query will Display the NULL value under the column heading DepartmentName.

Right Outer Join


If we want to get all the departments name and employee id, employee first name, and employees last name of all the employees belonging to the department regardless of whether a department have employees or not, then we can use the right outer join. In this case we keep the Department table on the right side of the join clause. It will insert NULL values for the data which is missing in the left table (Employee).

Query for Right Outer Join


Collapse | Copy Code

SELECT Dept.DepartmentName, Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName FROM Employee Emp RIGHT OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmentid

Result
Collapse | Copy Code

DepartmentName Empid EmpFirstName EmpLastName

Accounts Admin Admin HR Technology

2 1 3 NULL NULL

Amit Samir Neha NULL NULL

Kumar Singh Sharma NULL NULL

Explanation
Since we have use the Right Outer Join, this query will join the two tables Employee and Department on the basis of the values contains in the column Departmenttid. It will give the department name from the Department table and the Employee id, Employee first name, and Employee last name of all the employees that belong to that department. If any department does not contain any employee then it insert NULL value in the columns coming from the Employee table. Since no employee is connected to the departments HR and Technology, this query will display NULL values under the columns Empid, EmpFirstName and EmpLastName for the Departments HR and Technology. Since the department Admin and Accounts contains the employees therefore the columns Empid, EmpFirstName and EmpLastName contains the information, employee id, employee first name and employee last name respectively.

Full Outer Join


If we want to get all the departments name and the employee id, employee first name, employes last name of all the employees regardless of whether a department have employees or not, or whether a employee belong to a department or not, then we can use the full outer join. It will insert null values for the data which is missing in both the tables.

Query for Full Outer Join


Collapse | Copy Code

SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp FULL OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid

Result
Empid 1 2 3 4 NULL NULL EmpFirstName Samir Amit Neha Vivek NULL NULL EmpFirstName Singh Kumar Sharma Kumar NULL NULL DepartmentName Admin Accounts Admin NULL HR Technology

Explanation

Since we have used the Full Outer Join, this query will give the name of all the departments from the Department table and the Employee id, Employee first name, Employee last name of all the employees from the Employee table. If any department does not contain any employee, then it insert NULL value in the columns Empid, EmpFirstName, EmpLastName columns and if any employee doesn't belong to any department then it insert NULL value in the column DepartmentName. Here since Vivek Kumar doesn't belong to any department, the result displays NULL value under the column DepartmentName. Since the departments HR and Accounts don't contain any employees, the result of the above query displays NULL values under the columns Empid, EmpFirstName and EmpLastName for the departments HR and Technology..

Cross Join
This join combines all the rows from the left table with every row from the right table. This type of join is needed when we need to select all the possible combinations of rows and columns from both the tables. This type of join is generally not preferred as it takes lot of time and gives a huge result that is not often useful.

Query for the Cross Join


SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp CROSS JOIN Department dept

Results
Empid 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 EmpFirstName Samir Amit Neha Vivek Samir Amit Neha Vivek Samir Amit Neha Vivek Samir Amit Neha Vivek EmpLastName Singh Kumar Sharma Kumar Singh Kumar Sharma Kumar Singh Kumar Sharma Kumar Singh Kumar Sharma Kumar DepartmentName Accounts Accounts Accounts Accounts Admin Admin Admin Admin HR HR HR HR Technology Technology Technology Technology

Explanation
This Cross Join query will give combines all the rows from the Employee table with every row of the Department table. Since the Employee table contains 4 rows and the Department table contains 4 rows, therefore this result will returns 4*4=16 rows. This query doesn't contain any ON clause.

You might also like