Alternative methods 1

Improving Query Performance in SQL Server

Dean Smith

Founder, Atamai Analytics

EXISTS

SELECT CustomerID,
       CompanyName,
       ContactName 
FROM Customers c
WHERE EXISTS
        (SELECT 1 
         FROM Orders o
         WHERE c.CustomerID = o.CustomerID);
CustomerID CompanyName ContactName
ALFKI Alfreds Futterkiste Maria Anders
LAUGB Laughing Bacchus Wine Cellars Yoshi Tannamuri
QUICK QUICK-Stop Horst Kloss
... ... ...
Improving Query Performance in SQL Server

IN

SELECT CustomerID,
       CompanyName,
       ContactName 
FROM Customers
WHERE CustomerID IN
        (SELECT CustomerID 
         FROM Orders);
CustomerID CompanyName ContactName
ALFKI Alfreds Futterkiste Maria Anders
LAUGB Laughing Bacchus Wine Cellars Yoshi Tannamuri
QUICK QUICK-Stop Horst Kloss
... ... ...
Improving Query Performance in SQL Server

EXISTS vs. IN

 

  • EXISTS will stop searching the sub-query when the condition is TRUE

 

  • IN collects all the results from a sub-query before passing to the outer query

 

  • Consider using EXISTS instead of IN with a sub-query
Improving Query Performance in SQL Server

NOT EXISTS

SELECT CustomerID,
       CompanyName,
       ContactName 
FROM Customers c
WHERE NOT EXISTS 
        (SELECT 1 
         FROM Orders o
         WHERE c.CustomerID = o.CustomerID);
CustomerID CompanyName ContactName
FISSA FISSA Fabrica Inter. Salchichas S.A. Diego Roel
PARIS Paris spécialités Marie Bertrand
Improving Query Performance in SQL Server

NOT IN

SELECT CustomerID,
       CompanyName,
       ContactName 
FROM Customers
WHERE CustomerID NOT IN
        (SELECT CustomerID 
         FROM Orders);
CustomeID CompanyName ContactName
FISSA FISSA Fabrica Inter. Salchichas S.A. Diego Roel
PARIS Paris spécialités Marie Bertrand
Improving Query Performance in SQL Server

NOT IN and NULLs

SELECT UNStatisticalRegion AS UN_Region
      ,CountryName
      ,Capital
FROM Nations
WHERE Capital NOT IN 
        (SELECT NearestPop 
         FROM Earthquakes);
UN_Region CountryName Capital
Improving Query Performance in SQL Server

Handling NOT IN NULLs

SELECT UNStatisticalRegion AS UN_Region
      ,CountryName
      ,Capital
FROM Nations
WHERE Capital NOT IN 
        (SELECT NearestPop 
         FROM Earthquakes
         WHERE NearestPop IS NOT NULL);
UN_Region CountryName Capital
South Asia India New Delhi
East Asia and Pacific Indonesia Jakarta
East Asia and Pacific East Timor Dili
Sahara Africa Comoros Moroni
... ... ...
Improving Query Performance in SQL Server

EXISTS, NOT EXISTS, IN and NOT IN

Advantages

  • Results can contain any column from the outer query, and in any order

Disadvantages

  • The way NOT IN handles NULL values in the sub-query
Improving Query Performance in SQL Server

Let's practice!

Improving Query Performance in SQL Server

Preparing Video For Download...