+ 8

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

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

13th Dec 2016, 12:13 PM
Akwin Lopez
Akwin Lopez - avatar
5 odpowiedzi
+ 4
Thanks for the tip
9th Jan 2017, 5:44 AM
CodingForFun
CodingForFun - avatar
+ 1
thanks for that information
10th Nov 2018, 7:01 AM
Seelam Hari narayana Reddy
Seelam Hari narayana Reddy - avatar
0
Thanks for the heads up
14th Aug 2018, 8:13 AM
Marothi Mahlake
Marothi Mahlake - avatar
0
🤗
26th Nov 2018, 1:24 PM
Shashank Dixit
Shashank Dixit - avatar
0
nice tip bro
3rd Dec 2018, 1:59 AM
Ambarish