SQL Articles

SQL Server performance tip - Do not use NOT IN clause in Subquery use LEFT OUTER JOIN instead


Do not use NOT IN clause in sub query, instead of this use LEFT OUTER JOIN shown in below example query. This will reduce the execution time and improves the performance.

To know more details with examples, create two sample tables Employees and ResginedEmployees.

CREATE TABLE Employees(EmpID INT,Name VARCHAR(50))
INSERT INTO Employees VALUES(1,'Steve')
INSERT INTO Employees VALUES(2,'Brown')
INSERT INTO Employees VALUES(3,'Smith')
INSERT INTO Employees VALUES(4,'Chris')
INSERT INTO Employees VALUES(5,'Andrew')

CREATE TABLE ResginedEmployees(EmpID INT,Date DATETIME)
insert into ResginedEmployees VALUES(3,'2008-01-01')
insert into ResginedEmployees VALUES(4,'2009-01-01')

Normal query to get all employees who are not resigned is,

SELECT * FROM Employees WHERE EmpID NOT IN (SELECT EmpID FROM ResginedEmployees)
This query execution time would degrade the performance. The best way to write the query for the same result is use LEFT OUTER JOIN and use NULL value to any column of second table in where condition as shown below.
SELECT * FROM Employees E LEFT OUTER JOIN ResginedEmployees R on E.EmpID=R.EmpID
WHERE R.EmpID is NULL

Note that you can use R.DATE is NULL (any column from second table with NULL value) in where condition for same result.

Output

Query optimization example