SQL SERVER

Advanced Joins

Advanced Joins

1. Advanced or intelligent joins in SQL Server
2. Retrieve only the non matching rows from the left table
3. Retrieve only the non matching rows from the right table
4. Retrieve only the non matching rows from both the left and right table

Considers Employees (tblEmployee) and Departments (tblDepartment) tables

Employee Table (tblEmployee)

Employee+Table

Departments Table (tblDepartment)

Departments+Table
How to retrieve only the non matching rows from the left table. The output should be as shown below:
Only+Left+Table+Rows

Query:
SELECT       Name, Gender, Salary, DepartmentName
FROM           tblEmployee E
LEFT JOIN   tblDepartment D
ON                 E.DepartmentId = D.Id
WHERE        D.Id IS NULL

Left+only+join

How to retrieve only the non matching rows from the right table

Only+Right+Table+Rows

Query:
SELECT         Name, Gender, Salary, DepartmentName
FROM             tblEmployee E
RIGHT JOIN    tblDepartment D
ON                   E.DepartmentId = D.Id
WHERE          E.DepartmentId IS NULL

Right+only+join

How to retrieve only the non matching rows from both the left and right table. Matching rows should be eliminated.
Only+Left+and+Right+Table+Rows

Query:
SELECT         Name, Gender, Salary, DepartmentName
FROM              tblEmployee E
FULL JOIN      tblDepartment D
ON                   E.DepartmentId = D.Id
WHERE          E.DepartmentId IS NULL
OR                   D.Id IS NULL

Left+and+right+only+join

About the author

shohal

Leave a Comment