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

SQL Server-4 - JOINS

The document discusses different types of joins in SQL Server including inner, outer, left, right, and full outer joins. It provides examples of each join type using sample Employee and Projects tables, showing how each join returns or excludes matching and non-matching records.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

SQL Server-4 - JOINS

The document discusses different types of joins in SQL Server including inner, outer, left, right, and full outer joins. It provides examples of each join type using sample Employee and Projects tables, showing how each join returns or excludes matching and non-matching records.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

SQL Server – JOINS

What are the different types of joins available in SQL Server?


The SQL Server Joins are classified into two types such as
1. ANSI format JOINS
2. NON-ANSI format JOINS

Again the ANSI format joins classified into three types such as
1. Inner join
2. Outer join
3. Cross join
Further, the outer join is divided into three types are as follows
1. Left outer join
2. Right outer join
3. Full outer join

NON-ANSI join in SQL Server are classified into four types such as
1. EQUI join
2. NON-EQUI join
3. SELF-join
4. Natural Join

Examples to Understand Joins in SQL Server:


We are going to use the following Employee and Projects tables to understand the SQL
Server Joins. The EmployeeId column in the Projects table is the foreign key referencing to
the Id column of the Employee table. The Id column is the Primary key column in the
Employee table.
Please use the following SQL Script to create the Company database, Employee, and
Projects tables with the required sample data.
-- Create Company Database
CREATE DATABASE Company;
-- Create Employee Table
CREATE TABLE Employee (
Id INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Department VARCHAR(100) NOT NULL,
Salary FLOAT NOT NULL,
Gender VARCHAR(45) NOT NULL,
Age INT NOT NULL,
City VARCHAR(45) NOT NULL
);
-- Populate Employee Table
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1001, 'John Doe', 'IT', 35000, 'Male', 25, 'London');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1002, 'Mary Smith', 'HR', 45000, 'Female', 27, 'London');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1003, 'James Brown', 'Finance', 50000, 'Male', 28, 'London');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1004, 'Mike Walker', 'Finance', 50000, 'Male', 28, 'London');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1005, 'Linda Jones', 'HR', 75000, 'Female', 26, 'London');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1006, 'Anurag Mohanty', 'IT', 35000, 'Male', 25, 'Mumbai');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1007, 'Priyanla Dewangan', 'HR', 45000, 'Female', 27, 'Mumbai');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1008, 'Sambit Mohanty', 'IT', 50000, 'Male', 28, 'Mumbai');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1009, 'Pranaya Kumar', 'IT', 50000, 'Male', 28, 'Mumbai');
INSERT INTO Employee (Id, Name, Department, Salary, Gender, Age, City) VALUES
(1010, 'Hina Sharma', 'HR', 75000, 'Female', 26, 'Mumbai');
-- Create Projects Table
CREATE TABLE Projects (
ProjectId INT PRIMARY KEY IDENTITY(1, 1),
Title VARCHAR(200) NOT NULL,
ClientId INT,
EmployeeId INT,
StartDate DATETIME,
EndDate DATETIME,
FOREIGN KEY (EmployeeId) REFERENCES Employee(Id)
);
-- Populate Projects Table
INSERT INTO Projects (Title, ClientId, EmployeeId, StartDate, EndDate) VALUES
('Develop ecommerse website from scratch', 1, 1003, GETDATE(), (Getdate() + 35)),
('WordPress website for our company', 1, 1002, GETDATE(), (Getdate() + 45)),
('Manage our company servers', 2, 1007, GETDATE(), (Getdate() + 55)),
('Hosting account is not working', 3, 1009, GETDATE(), (Getdate() + 65)),
('MySQL database from my desktop application', 4, 1010, GETDATE(), (Getdate() + 75)),
('Develop new WordPress plugin for my business website', 2, NULL, GETDATE(),
(Getdate() + 85)),
('Migrate web application and database to new server', 2, NULL, GETDATE(), (Getdate() +
95)),
('Android Application development', 4, 1004, GETDATE(), (Getdate() + 60)),
('Hosting account is not working', 3, 1001, GETDATE(), (Getdate() + 70)),
('MySQL database from my desktop application', 4, 1008, GETDATE(), (Getdate() + 80)),
('Develop new WordPress plugin for my business website', 2, NULL, GETDATE(),
(Getdate() + 90));

Inner Join in SQL Server


The Inner Join in SQL Server is used to return only the matching rows from both the tables
involved in the join by removing the non-matching records. The following diagram shows the
pictorial representation of SQL Server Inner Join.
Syntax to use Inner Join in SQL Server:
Please have a look at the following image which shows the syntax of Inner Join in the SQL
Server database. In SQL Server, you can use either the INNER JOIN or JOIN keyword to
perform Inner Join. If you use only the JOIN keyword, then it is also going to perform Inner
JOIN in SQL Server.

Inner Join Example in SQL Server:


Our requirement is to retrieve the EmployeeId, Name, Department, City, Title as Project,
and ClientId from the Employee and Projects tables. So, basically, we want the following
result set as our output.

Following is the SQL Server Inner Join Query that is joining the Employee and Projects
tables and gives you the result set as shown in the above image. Here, we are using the
EmployeeId column to check the similar values on the ON clause as both the tables having
this column (Id in Employee table and EmployeeId in Projects table).
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
INNER JOIN Projects
ON Employee.Id = Projects.EmployeeId;

If you look at the output, here, we got 8 rows. We did not get those 3 records that have the
NULL value in the EmployeeId column of the Projects table. So, this proves that the Inner
Join in SQL Server is used to return only the matching records from both the tables involved
in the join. The non-matching records are simply ignored or eliminated.
Instead of using the INNER JOIN keyword, we can also use the JOIN keyword as shown in
the below Query, and we will also get the same output as the previous example. This also
proofs that the default joins in SQL Server is Inner Join.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
JOIN Projects
ON Employee.Id = Projects.EmployeeId;

Outer Join in SQL Server


The OUTER JOIN in SQL Server returns matched data rows as well as unmatched data
rows from both the tables involved in the join. Outer join in SQL Server is again classified
into three types as follows.
1. Left outer join
2. Right outer join
3. Full outer join

Left Outer Join in SQL Server


The LEFT OUTER JOIN in SQL Server is used to retrieve all the matching rows from both
the tables involved in the join as well as non-matching rows from the left side table. In this
case, the un-matching data will take a null value.
The question that should come to your mind is, which is the left table and which is the right
table? The answer is, the table mentioned to the left of the LEFT OUTER JOIN keyword is
the left table, and the table mentioned to the right of the LEFT OUTER JOIN keyword is the
right table. The following diagram is the pictorial representation of SQL Server Left Outer
Join.

Syntax to use Left Outer Join in SQL Server:


Please have a look at the following image which shows the syntax of Left Outer Join in SQL
Server. In SQL Server, you can use either the LEFT OUTER JOIN or LEFT JOIN keyword
to perform Left Outer Join. If you only use the LEFT JOIN keyword, then it is also going to
perform LEFT OUTER JOIN in SQL Server.

Example to Understand Left Outer Join in SQL Server


Now, we need to write a query to retrieve the Id as EmployeeId, Name, Department, City,
and Title as Project from the Employee and Projects tables. So, basically, we want the
query to produce the following result set as output. As you can see in the output, we are
retrieving all the matching records from both the table as well as the non-matching records
from the Employee table.

Now using SQL Server LEFT OUTER JOIN, we can join the Employee and Projects table
and display the information of the employees and the projects they are working on, we also
get the details of employees who are not working on any project and in that case, the
Project and ClientId column will take NULL values. The Following Query will give you the
results as shown in the above image.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
LEFT OUTER JOIN Projects
ON Employee.Id = Projects.EmployeeId;
If you look at the output, here, we got all 10 records (i.e. all the records from
the Employee Table) including the row that has a null value for the EmployeeId column in
the Projects table. So, this proofs that the Left Outer Join will retrieve all the rows from
the Left-hand side Table including the rows that have a null foreign key value in the right-
hand side table.
Instead of using the LEFT OUTER JOIN keyword, you can also use
the LEFT JOIN keyword as shown in the below Query, and also you will get the same
output as the previous query.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
LEFT JOIN Projects
ON Employee.Id = Projects.EmployeeId;

Right Outer Join in SQL Server


The RIGHT OUTER JOIN in SQL Server is used to retrieve all the matching rows from both
the tables involved in the join as well as non-matching rows from the right-side table. In this
case, the un-matching data will take NULL values.
The question that should come to your mind is, which is the left table and which is the right
table? The answer is, the table mentioned to the left of the RIGHT OUTER JOIN keyword is
the left table, and the table mentioned to the right of the RIGHT OUTER JOIN keyword is
the right table. The following diagram is the pictorial representation of SQL Server Right
Outer Join.

Syntax to use Right Outer Join in SQL Server:


Please have a look at the following image which shows the syntax of Right Outer Join in
SQL Server. In SQL Server, you can use either the RIGHT OUTER JOIN or RIGHT JOIN
keyword to perform Right Outer Join. If you only use the RIGHT JOIN keyword, then it is
also going to perform RIGHT OUTER JOIN in SQL Server.

Example to Understand Right Outer Join in SQL Server


Now, we need to write a query to retrieve the Id as EmployeeId, Name, Department, City,
and Title as Project from the Employee and Projects tables. So, basically, we want the
query to produce the following result set as output. As you can see in the output, we are
retrieving all the matching records from both the table as well as the non-matching records
from the Projects table.

Now using SQL Server RIGHT OUTER JOIN, we can join Employee and Projects table and
display the information of employees and the projects they are working on, we also get the
details of projects which are not yet assigned to any employee. The Following Query will
give you the results as shown in the above image.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
RIGHT OUTER JOIN Projects
ON Employee.Id = Projects.EmployeeId;

If you look at the output, here, we got all 11 rows (i.e. all the rows from the Projects Table).
If you further notice, here, we got all the matching records from both the Employee and
Projects tables as well as all non-matching rows from the right-side table i.e. the Projects
Table. So, this proofs that the Right Outer Join retrieves all the rows from the Left-hand side
Table including the rows that have a null foreign key value in the left-hand side table.
Instead of using the RIGHT OUTER JOIN keyword, we can also use
the RIGHT JOIN keyword as shown in the below SQL Query, and also get the same output
as the previous query.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
RIGHT JOIN Projects
ON Employee.Id = Projects.EmployeeId;

Full Outer Join in SQL Server


The Full Outer Join in SQL Server is used to retrieve all the matching records as well as all
the non-matching records from both the tables involved in the JOIN. The Un-matching data
in such cases will take the NULL values. The following diagram shows the pictorial
representation of Full Outer Join in SQL Server.

Syntax to use Full Outer Join in SQL Server:


Please have a look at the following image which shows the syntax of Full Outer Join in SQL
Server. In SQL Server, you can use either the FULL OUTER JOIN or FULL JOIN keyword
to perform Full Outer Join. If you only use the FULL JOIN keyword, then it is also going to
perform FULL OUTER JOIN in SQL Server.
Example to Understand Full Outer Join in SQL Server
Now, we need to write a query to retrieve the Id as EmployeeId, Name, Department, City,
and Title as Project from the Employee and Projects tables. So, basically, we want the
query to produce the following output. As you can see in the output, we are retrieving all the
matching records as well as all the non-matching records from both the table.

Now using SQL Server FULL OUTER JOIN, we can join Employee and Projects table and
display the information of employees and the projects they are working on, we also get the
details of projects which are not yet assigned to any employee as well as all the employees
who are not assigned with any projects. The Following Query will give you the results as
shown in the above image.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
FULL OUTER JOIN Projects
ON Employee.Id = Projects.EmployeeId;

If you look at the output, here, we got all 13 rows (i.e. all the rows from the Projects Table
as well as all the rows from the Employee table). Instead of using the FULL OUTER
JOIN keyword, we can also use the FULL JOIN keyword as shown in the below Query, and
get the same output as the previous query.
SELECT Id as EmployeeID, Name, Department, City, Title as Project, ClientId
FROM Employee
FULL JOIN Projects
ON Employee.Id = Projects.EmployeeId;

Cross Join in SQL Server


The CROSS JOIN is created by using the CROSS JOIN keyword. The CROSS JOIN does
not contain an ON clause. In Cross Join, each record of a table is joined with each record of
the other table. In SQL Server, the Cross Join should not have either an ON or where
clause.

Example to Understand CROSS JOIN in SQL Server:


A Cross Join in SQL Server produces the Cartesian product of the tables involved in the
join. The Cartesian product means the number of records present in the first table is
multiplied by the number of records present in the second table. Please have a look at the
below SQL query which is an example of Cross Join for joining the Employee and Projects
Table.
SELECT Employee.Id as EmployeeId, Name, Department, City, Title as Project
FROM Employee
CROSS JOIN Projects;
The Employee is the LEFT Table which contains 10 rows and Projects is the RIGHT Table
which contains 11 rows. So, when you execute the above query, you will get 110 records in
the result set.

What is Self-Join in SQL Server?


Joining a table by itself is called self-join in SQL Server. When we have some relation
between the columns within the same table then we need to use the self-join mechanism.
When we implement the self-join in SQL Server, we should create the alias for the table
name. We can create any number of aliases for a single table. Self-join is not a different
kind of join. It can be classified as any type of join, such as
1. Inner Join
2. Outer (Left, Right, Full) join
3. Cross Join
Note: The Self-join in SQL Server is just like any other joins except that the two instances of
the same table will be joined in the query.

What is the difference between Union and Join in SQL Server?


Joins and Unions are two different things. The Union in SQL Server is used to combines the
result-set of two or more select queries into a single result-set. On the other hand, the Joins
in SQL Server are used to retrieve the data from two or more related tables involved in the
join.

What is the General Formula for Joins in SQL Server?

2.Inner Join in SQL Server

The Inner Join in SQL Server is used to returns only the matching rows from both the tables
involved in the join by removing the non-matching rows. That means Inner join results only
the matching rows from both the tables involved in the join. The following diagram shows
the pictorial representation of Inner Join.

How to implement Inner Join in SQL Server?


Please have a look at the following image which shows the syntax of SQL Server Inner
Join. Here, you can use either the INNER JOIN or JOIN keyword to perform Inner Join. If
you use only the JOIN keyword, then it is also going to perform the Inner JOIN operation in
SQL Server.

When do we need to use Inner JOIN in SQL Server?


If you want to select all the rows from the Left table that have a non-null foreign key value
then you need to use SQL Server Inner Join. To simplify this we can say that if you want to
retrieve all the matching rows from both the tables then you need to use the Inner Join.
Example to Understand SQL Server Inner JOIN:
Let us understand how to implement Inner Join in SQL Server with an example. To
understand Inner Join in SQL Server, we are going to use the following Company and
Candidate tables.

Now, our requirement is to write a query, to retrieve the CandidateId, FullName,


CompanyId, and CompanyName from Company and Candidate tables. The output of the
query should be as shown below. That means we want only the matching records from both
tables.
Following is the Query which is an example of Inner Join that is joining the Company and
Candidate tables and will give the result as shown in the above image.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName

FROM Candidate Cand

INNER JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId;
If you look at the above output, we got only 5 rows. We did not get the 2 rows that have the
NULL value in the CompanyId column. Instead of using the INNER JOIN keyword, we can
also use the JOIN keyword as shown in the below SQL Query. JOIN or INNER JOIN means
the same. But it’s always better to use INNER JOIN, as this explicitly specifies your
intention.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName

FROM Candidate Cand

JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId
So, in short, we can say that the Inner Join is used to returns only the matching records
from both the tables involved in the join. The non-matching rows are simply eliminated.

Joining three Tables in SQL Server:


Now we will see how to JOIN three tables in SQL Server. Already we have Company and
Candidate tables. Let us introduce the third table i.e. the Address table. So, we are going to
use the following Address table along with the Company and Candidate tables.
The following is the syntax to join three tables in SQL Server.

Example: Inner Joining Candidate, Company, and Address tables


The following Inner Join SQL Query Joining Candidate, Company, and Address tables.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName,

Addr.Country,

Addr.State,

Addr.City

FROM Candidate Cand

INNER JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

INNER JOIN Address Addr

ON Addr.CandidateId = Cand.CandidateId;
When you execute the above query, you will get the following output. Now you can see, we
got only three records, this is because the following three records exist in all the three
tables.

It is also possible to use Different types of Joins while joining three tables in SQL Server.
For example, in the below SQL Query, we perform the first join (between Candidate and
Company) using Inner JOIN and the second join (between Candidate and Address)
operation using LEFT JOIN.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName,

Addr.Country,

Addr.State,

Addr.City

FROM Candidate Cand

INNER JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

LEFT JOIN Address Addr

ON Addr.CandidateId = Cand.CandidateId;
When you execute the above SQL Query, you will get the following output. In this case, for
the left join between Candidate and Campany, it will take null values for Country, State, and
City column which does not have any reference.
Note: You need to use Inner JOIN when you want to retrieve only the matching records
from both the tables involved in the JOIN by eliminating the non-matching records from both
the tables. In most real-time applications, we need to use this JOIN

3.Left Outer Join in SQL Server

The Left Outer Join in SQL Server is used to retrieve the matching records from both the
tables as well as the non-matching records from the left side table involved in the JOIN. In
that case, the un-matching data will take the null value. If this is not clear at the moment
then don’t worry we will see it with an example. The following diagram shows the pictorial
representation of the Left Outer Join.

The question that should come to your mind is which is the left table and which is the right
table? The answer is, the table which is mentioned to the left of the LEFT OUTER JOIN
keyword is the left table, and the table which is mentioned to the right of the LEFT OUTER
JOIN keyword is the right table.
How to implement Left Outer Join in SQL Server?
Please have a look at the following image which shows the syntax of Left Outer Join in SQL
Server. Here, you can use either the Left Outer Join or the Left Join keywords to perform
the Left Outer Join operation. If you use only the Left JOIN keyword, then also it is going to
perform the Left Outer Join operation.

When do we need to use Left JOIN or Left Outer Join in SQL Server?
If you want to select all the records from the Left side table including the records that have a
null foreign key value then you need to use the SQL Server Left Outer Join. To simplify the
above definition, we can say that if you want to retrieve all the matching records from both
the tables involved in the join as well as the non-matching records from the left side table
then we need to use Left Join or Left Outer Join in SQL Server.

Example to Understand Left Outer Join in SQL Server.


Let us understand how to implement Left Outer Join in SQL Server with Examples. To
understand Left Outer Join in SQL Server, we are going to use the following Company and
Candidate tables.
Now our requirement is to write a query, to retrieve the CandidateId, FullName, CompanyId,
and CompanyName from Company and Candidate tables. The output of the query should
be as shown below.

Following is the SQL Query which is an example of Left Outer Join that is joining the
Company and Candidate tables and will give the results shown in the above image.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

LEFT OUTER JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId;
If you look at the output, here, we got all 7 rows (i.e. all the rows from the Candidate Table)
including the row that has a null value for the CompanyId column. So this proofs that the
SQL Server Left Outer Join will retrieve all the rows from the Left-hand side Table including
the rows that have a null foreign key value.
Instead of using the Left Outer Join keyword, we can also use the Left Join keyword. This
will also work as expected as Left Outer Join. That means the Left Outer Join or Left Join
means the same. Following is the SQL Query that uses Left Join Keyword to join Candidate
and Company tables.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,
Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

LEFT JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId;
In short, we can say that Left Outer Join will return all the matching records from both the
tables involved in the join as well as all the non-matching records from the left-hand side
table. Now, let us proceed and understand some tricky questions which may be asked in
SQL Server interviews.

How to retrieve only the non-matching rows from the left table in SQL
Server?
Here, what we want is, we want to retrieve only the non-matching records from the left
table. For example, we want the following result sets when we join the Candidate and
Company tables. If you further notice, here we want to retrieve those rows from the
Candidate table whose does not have any reference in the Company table.

As we already discussed, the Left Outer Join is used to fetch all the matching records from
both the tables as well as all the non-matching records from the left-hand side table. In this
case, the non-matching records will take NULL value. So, to get the above output what we
need to do is, we need to perform Left Outer Join, and then in the where condition we need
to filter out the records which have NULL values. The following Left OuterJoin Query with
the where clause does the same.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

LEFT JOIN Company Comp


ON Cand.CompanyId = Comp.CompanyId

WHERE Comp.CompanyId IS NULL;

Joining three Tables in SQL Server using Left Join:


Now we will see how to join three tables in SQL Server. Already we have the Company and
Candidate tables. Let us introduce the third table i.e. the Address table. So, we are going to
use the following Address table along with the Company and Candidate tables to perform
joining operations between three tables in SQL Server.

The following is the syntax to join three tables in SQL Server.

Example: Left Joining Candidate, Company, and Address tables


The following Left Join SQL Query Joining Candidate, Company, and Address tables.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName,

Addr.Country,

Addr.State,

Addr.City
FROM Candidate Cand

LEFT JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

LEFT JOIN Address Addr

ON Addr.CandidateId = Cand.CandidateId;
When you execute the above SQL Query, you will get the following output.

Note: You need to use LEFT OUTER JOIN when you want to retrieve all the matching
records from both the tables involved in the JOIN as well as non-matching records from the
left-hand side table.

4.Right Outer Join in SQL Server

The Right Outer Join in SQL Server is used to retrieve all the matching records from both
the tables involved in the join as well as all the non-matching records from the right-hand
side table. In that case, the un-matching data will take the null value. The following diagram
shows the pictorial representation of the Right Outer Join in SQL Server.
The question that should come to your mind is which is the left table and which is the right
table? The answer is, the table which is mentioned to the left of the RIGHT OUTER JOIN
keyword is the left table, and the table which is mentioned to the right of the RIGHT OUTER
JOIN keyword is the right table. The following diagram shows the pictorial representation of
Right Outer Join.

How to implement Right Outer Join in SQL Server?


Please have a look at the following image which shows the syntax of Right Outer Join.
Here, you can use either the Right Outer Join or Right JOIN keyword to perform the Right
Outer Join operation. If you use only the Right JOIN keyword, then it is also going to
perform Right Outer Join in SQL Server.
When do we need to use the Right JOIN in SQL Server?
If you want to select all the records from the Right side table including the records that have
a null foreign key value then you need to use the SQL Server Right Outer Join. To simplify
the above definition, we can say that if you want to retrieve all the matching rows from both
the tables involved in the join as well as the non-matching rows from the right side table
then you need to use Right Outer Join in SQL Server.

Example to Understand SQL Server Right Outer Join.


Let us understand how to implement Right Outer Join in SQL Server with Examples. To
understand Right Outer Join, we are going to use the following Company and Candidate
tables.

Write a query, to retrieve CandidateId, FullName, CompanyId, and CompanyName from


Company and Candidate tables. The output of the query should be as shown below.

Following is the Query which is an example of Right Outer Join that is joining the Company
and Candidate tables and will give the results shown in the above image.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,
Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

RIGHT OUTER JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId
If you look at the above, we got 6 rows. We got all the matching rows from both the tables
as well as non-matching rows from the right side table i.e. the Company Table. Instead of
using the Right Outer Join keyword, you can also use the Right Join keyword. This will
also work as expected as Right Outer Join. That means the SQL Server Left Outer Join or
Left Join means the same. The following example uses the Right Join keyword and we also
get the same output as the previous example.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

RIGHT JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

In short, we can say that Right Outer Join will return all the matching records from both the
tables as well as all the non-matching records from the right-hand side table.

How to retrieve only the non-matching rows from the right table?
Here, what we want is, we want to retrieve only the non-matching records from the right
table. For example, we want the following result sets when we join the Candidate and
Company tables. If you further notice, here we want to retrieve those rows from the
Candidate table whose does not have any reference in the Company table.
As we already discussed, the Right Outer Join is used to fetch all the matching records from
both the tables as well as all the non-matching records from the right-hand side table. In this
case, the non-matching records will take NULL value. So, to get the above output what we
need to do is, we need to perform the Right Outer Join operation, and then in the where
condition we need to filter out the records which have NULL values. The following Right
OuterJoin Query with the where clause does the same.

SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

Right JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

WHERE Cand.CompanyId IS NULL;

Joining three Tables in SQL Server:


Now we will see how to Right Join three tables in SQL Server. Already we have the
Company and Candidate tables. Let us introduce the third table i.e. the Address table. So,
we are going to use the following Address table along with the Company and Candidate
tables to perform joining operations between three tables.

The following is the syntax to join three tables in SQL Server.


Example: Right Joining Candidate, Company, and Address tables
The following Right Join SQL Query Joining Candidate, Company, and Address tables.

SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName,

Addr.Country,

Addr.State,

Addr.City

FROM Candidate Cand

RIGHT JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

RIGHT JOIN Address Addr

ON Addr.CandidateId = Cand.CandidateId;

When you execute the above Right Join SQL Query, you will get the following output.
5.Full Outer Join in SQL Server

The Full Outer Join in SQL Server is used to retrieve all the matching records from both the
tables involved in the join as well as all the non-matching records from both the tables. The
Un-matching data in such cases will take the null value. The following diagram shows the
pictorial representation of Full Outer Join in SQL Server.

How to implement Full Outer Join in SQL Server?


Please have a look at the following image which shows the syntax of SQL Server Full Outer
Join. Here, you can use either the Full Outer Join or Full JOIN keyword to perform Full Join.
If you use only the Full JOIN keyword, then it is also going to perform Full Outer Join.
When do we need to use the Full Outer JOIN?
If you want to select all the records from the left-hand side table plus all the records from the
right-hand side table then you need to use the SQL Server Full Outer Join. To simplify this
we can say that if you want to retrieve all the matching rows as well as all the non-matching
rows from both the tables involved in the join then you need to use Full Outer Join in SQL
Server.

Example to Understand SQL Server Full Outer Join.


Let us understand how to implement Full Outer Join in SQL Server with Examples. To
understand Full Outer Join, we are going to use the following Company and Candidate
tables.

Our requirement is to write a query, to retrieve CandidateId, FullName, CompanyId, and


CompanyName from Company and Candidate tables. The output of the query should be as
shown below.
Following is the Query which is an example of Full Outer Join that is joining the Company
and Candidate tables and will give the results shown in the above image.

SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

FULL OUTER JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

If you look at the output, now we now got 8 rows. That means all the records from the
Candidate Table as well as all the records from the Company Table. Instead of using the
Full Outer Join keyword, you can also use the Full Join keyword. This will also work as
expected as Full Outer Join. That means the SQL Server Full Outer Join or Full Join means
the same. The following example uses Full Join Keyword to join both tables.

SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,
Comp.CompanyName

FROM Candidate Cand

FULL JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

In short, Full Outer Join, or you can say Full Join will return all the records from both left and
right tables involved in the join, including the non-matching rows.

How to retrieve only the non-matching rows from both the left and right
table?
Here, what we want is, we want to retrieve only the non-matching records from both tables.
For example, we want the following result sets when we join the Candidate and Company
tables. If you further notice, here all the matching rows are eliminated.

As we already discussed, the Full Outer Join is used to fetch all the matching records from
both the tables as well as all the non-matching records from both the table. In this case, the
non-matching records will take NULL value. So, to get the above output what we need to do
is, we need to perform Full Outer Join operation, and then in the where condition we need
to filter out the records which have NULL values. The following Full OuterJoin Query with
the where clause does the same.

SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyId,

Comp.CompanyName

FROM Candidate Cand

FULL JOIN Company Comp


ON Cand.CompanyId = Comp.CompanyId

WHERE Cand.CompanyId IS NULL

OR Comp.CompanyId IS NULL

Joining three Tables using Full Outer Join:


Now we will see how to Full Join three tables. Already we have the Company and
Candidate tables. Let us introduce the third table i.e. the Address table. So, we are going to
use the following Address table along with the Company and Candidate tables to perform
full outer joining operations between three tables.

The following is the syntax to join three tables in SQL Server.

Example: Joining Candidate, Company, and Address tables using Full


Outer Join
The following Query Joining Candidate, Company, and Address tables.
SELECT Cand.CandidateId,

Cand.FullName,

Cand.CompanyId,

Comp.CompanyName,

Addr.Country,

Addr.State,
Addr.City

FROM Candidate Cand

FULL JOIN Company Comp

ON Cand.CompanyId = Comp.CompanyId

FULL JOIN Address Addr

ON Addr.CandidateId = Cand.CandidateId;

When you execute the above Full Outer Join Query, you will get the below output.

6.Self Join in SQL Server

The Self Join is nothing a concept where we need to join a table by itself. You need to use
Self Join when you have some relations between the columns of the same table. If this is
not clear at the moment then don’t worry we will discuss this with an example. I am sure at
the end of this article, you definitely have a very good idea of when to and how to use SQL
Server Self Join.
The point that you need to remember that when you are implementing the self-join
mechanism then you need to create the alias for the table. You can also create any number
of aliases for a single table in SQL Server. The Self Join is not a different type of join. It can
be classified as any type of join, such as

1. Inner Join
2. Outer (Left, Right, Full) join
3. Cross Join
The Self Join is like any other join except that the two instances of the same table will be
joined in the query.
Let’s understand Self Join with Examples
We are going to use the following Employee table to understand the SQL Server Self Join
concept.

Self Join Examples in SQL Server:


The above Employee table contains the rows for both normal employees as well as
managers of that employee. So in order to find out the managers of each employee, we
need a SQL Server Self Join. So here we need to write a query that should give the
following result.

Self Join Query:


A MANAGER is also an EMPLOYEE. Both the EMPLOYEE and MANAGER rows are
present in the same Employee table. Here we are joining the
table Employee with itself using different alias names, E for Employee and M for Manager.
Here we are going to use the Left Outer Join to get the records with ManagerId NULL. You
can see in the output that Preety’s record is also retrieved, but the MANAGER is NULL. If
you replace LEFT JOIN with INNER JOIN, you will not get Preety’s record.
SELECT E.Name as Employee, M.Name as Manager

FROM Employee E

LEFT JOIN Employee M

ON E.ManagerId = M.EmployeeId

Inner Self Join Employee table:

SELECT E.Name as Employee, M.Name as Manager


FROM Employee E

INNER JOIN Employee M

ON E.ManagerId = M.EmployeeId
When we execute the above query it produces the output as shown below.

Cross Self Join Employee table:

SELECT E.Name as Employee, M.Name as Manager

FROM Employee E

CROSS JOIN Employee M

7.Cross Join in SQL Server

What is Cross Join?


When we combine two or more tables with each other without any condition (where or on)
then we call this type of joins Cartesian or cross join. In Cross Join, each record of a table is
joined with each record of the other table involved in the join. In SQL Server, the Cross Join
should not have either ON or where clause.

How to implement Cross Join in SQL Server?


Let us understand how to implement the Cross Join with an example. Let’s create two
Tables with the name Company and Candidate. Please use the below SQL Script to
create Company and Candidate tables and populate these two tables with some test data.
Please note that the CompanyId column of the Candidate table is a foreign key
referencing the CompanyId column of the Company Table.

CREATE TABLE Company


(
CompanyId TinyInt Identity Primary Key,
CompanyName Nvarchar(50) NULL
)
GO
INSERT Company VALUES('DELL')
INSERT Company VALUES('HP')
INSERT Company VALUES('IBM')
INSERT Company VALUES('Microsoft')
GO
CREATE TABLE Candidate
(
CandidateId tinyint identity primary key,
FullName nvarchar(50) NULL,
CompanyId tinyint REFERENCES Company(CompanyId)
)
GO
INSERT Candidate VALUES('Ron',1)
INSERT Candidate VALUES('Pete',2)
INSERT Candidate VALUES('Steve',3)
INSERT Candidate VALUES('Steve',NULL)
INSERT Candidate VALUES('Ravi',1)
INSERT Candidate VALUES('Raj',3)
INSERT Candidate VALUES('Kiran',NULL)
GO

A Cross Join produces the Cartesian product of the tables involved in the join. The
Cartesian product means the number of records present in the first table is multiplied by the
number of records present in the second table. Please have a look at the below SQL query
which will which is an example of Cross Join for joining the Candidate and Company Table.

SELECT Cand.CandidateId,
Cand.FullName,
Cand.CompanyId,
Comp.CompanyId,
Comp.CompanyName
FROM Candidate Cand
CROSS JOIN Company Comp

When we execute the above cross join query, it produces the result set as shown in the
image below.

Points to remember when working with Cross Join:


The Cross Join produces the Cartesian product of the tables involved in the join. This
means every row in the Left Table is joined to every row in the Right Table. The candidate
is LEFT Table and Company is RIGHT Table. In our example, we have 28 total numbers
rows in the result set. 7 rows in the Candidate table multiplied by 4 rows in the Company
Table.
In SQL Server, the Cross Join does not have an ON clause with a Join condition. All other
JOINS use the ON clause with a Join Condition. If you try to use an ON clause on a
CROSS JOIN then it will give you a syntax error.

You might also like