Improving Query Performance in SQL Server
Dean Smith
Founder, Atamai Analytics
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 |
... | ... | ... |
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 |
... | ... | ... |
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
EXISTS
instead of IN
with a sub-querySELECT 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 |
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 |
SELECT UNStatisticalRegion AS UN_Region
,CountryName
,Capital
FROM Nations
WHERE Capital NOT IN
(SELECT NearestPop
FROM Earthquakes);
UN_Region | CountryName | Capital |
---|---|---|
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 |
... | ... | ... |
Advantages
Disadvantages
Improving Query Performance in SQL Server