Metodi alternativi 1

Migliorare le prestazioni delle query 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
... ... ...
Migliorare le prestazioni delle query 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
... ... ...
Migliorare le prestazioni delle query in SQL Server

EXISTS vs. IN

 

  • EXISTS interrompe la ricerca nella sottoquery quando la condizione è TRUE

 

  • IN raccoglie tutti i risultati della sottoquery prima di passarli alla query esterna

 

  • Valuta EXISTS invece di IN con una sottoquery
Migliorare le prestazioni delle query 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
Migliorare le prestazioni delle query 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
Migliorare le prestazioni delle query in SQL Server

NOT IN e NULL

SELECT UNStatisticalRegion AS UN_Region
      ,CountryName
      ,Capital
FROM Nations
WHERE Capital NOT IN 
        (SELECT NearestPop 
         FROM Earthquakes);
UN_Region CountryName Capital
Migliorare le prestazioni delle query in SQL Server

Gestire NOT IN con NULL

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
... ... ...
Migliorare le prestazioni delle query in SQL Server

EXISTS, NOT EXISTS, IN e NOT IN

Vantaggi

  • I risultati possono includere qualsiasi colonna della query esterna, in qualsiasi ordine

Svantaggi

  • Come NOT IN gestisce i valori NULL nella sottoquery
Migliorare le prestazioni delle query in SQL Server

Facciamo pratica!

Migliorare le prestazioni delle query in SQL Server

Preparing Video For Download...