SQL Day 13: Advance Joins
LO1: Retrieve only non-matching rows from the left table
LO2: Retrieve only non-matching rows from the right table
LO3: Retrieve only non-matching rows from both the right and the left table
Prerequisite: Joins
Retrieve only non-matching rows from the left table
In the previous tutorial, we have seen that how to retrieve the matching rows + non-matching from left the table using Left Outer Join.
Now here we are finding only the non-matching rows from the left table as you can see in below figure.
So to achieve the above result, we can use the IS NULL with where clause.
Let’s see how we can use the IS NULL to filter out the rows using where clause in Left Outer Join.
In table tblemployee we have the record that has DepartmentID is NULL as you can see in the below figure.
When we apply left outer join on tblemployee and tbldepartment table then we get the matching rows from the left table as well as non-matching rows from the left table.
select Name, Email, Salary, DepartmentName
from tblEmployee e
LEFT Join tblDepartment d
ON e.DepartmentID=d.ID
In above figure, employee Tim has departmentid NULL
So what our intention is to get only the non-matching rows from the left table i.e. to get only the Tim record, to do that we need to add the where clause with IS NULL
select Name, Email, Salary, DepartmentName
from tblEmployee e
LEFT Join tblDepartment d
ON e.DepartmentID=d.ID
Where e.DepartmentID IS NULL
In this way, we can find only the non-matching rows from the left table.
Retrieve only non-matching rows from the right table
Here we are finding only the non-matching rows from the right table as you can see in below figure.
The query will be the same as left outer join but this time we need to use the right join instead of left outer join.
select Name, Email, Salary, DepartmentName
from tblEmployee e
Right Join tblDepartment d
ON e.DepartmentID=d.ID
Where e.DepartmentID IS NULL
This will get the non-matching rows from the right table.
Retrieve only non-matching rows from both the right and the left table
As we see in the previous session that Full outer join will retrieve non-matching rows from both the table + matching rows from the both the table.
Now we have to only retrieve the non-matching rows both the tables as below figure.
To retrieve only the non-matching rows we need run the below query.
select Name, Email, Salary, DepartmentName
from tblEmployee e
FULL Join tblDepartment d
ON e.DepartmentID=d.ID
Where e.DepartmentID IS NULL
OR d.id IS NULL
So these are the ways to find out the only the non-matching rows from the tables.
That’s all for today. Thank You.
Comments
Post a Comment