SQL SERVER – Convert IN to EXISTS – Performance Talk
        Posted  
        
            by pinaldave
        on SQL Authority
        
        See other posts from SQL Authority
        
            or by pinaldave
        
        
        
        Published on Sat, 05 Jun 2010 01:30:36 +0000
        Indexed on 
            2010/06/05
            6:03 UTC
        
        
        Read the original article
        Hit count: 939
        
sql
|SQL Authority
|SQL Optimization
|SQL Performance
|SQL Query
|SQL Server
|SQL Tips and Tricks
|T SQL
|Technology
In recent training one of the attendee asked if I can show simple method to convert IN clause to EXISTS clause. Here is the simple example.
USE AdventureWorks
GO
-- use of =
SELECT *
FROM HumanResources.Employee E
WHERE E.EmployeeID = ( SELECT EA.EmployeeID
FROM HumanResources.EmployeeAddress EA
WHERE EA.EmployeeID = E.EmployeeID)
GO
-- use of exists
SELECT *
FROM HumanResources.Employee E
WHERE EXISTS ( SELECT EA.EmployeeID
FROM HumanResources.EmployeeAddress EA
WHERE EA.EmployeeID = E.EmployeeID)
GO
It is NOT necessary that every time when IN is replaced by EXISTS it gives better performance. However, in our case listed above it does for sure give better performance.
Click on below image to see the execution plan.

Reference: Pinal Dave (http://blog.SQLAuthority.com)
Filed under: SQL, SQL Authority, SQL Optimization, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology   
 
 
 
 

© SQL Authority or respective owner