Improving Query Performance in SQL Server
Dean Smith
Founder, Atamai Analytics
SELECT OrderID,
CustomerID,
NumDays
FROM
(SELECT *,
DATEDIFF(DAY,OrderDate,ShippedDate) AS NumDays
FROM Orders) AS o
WHERE NumDays >= 35;
OrderID | CustomerID | NumDays |
---|---|---|
10380 | HUNGO | 35 |
10427 | PICCO | 35 |
10545 | LAZYK | 35 |
10593 | LEHMS | 35 |
10660 | HUNGC | 37 |
10777 | GOURL | 37 |
10924 | BERGS | 35 |
SELECT CustomerID
,CompanyName
FROM Customers
WHERE CustomerID
IN (SELECT CustomerID
FROM Orders
WHERE Freight > 800);
CustomerID | CompanyName |
---|---|
QUEEN | Queen Cozinha |
QUICK | QUICK-Stop |
SAVEA | Save-a-lot Markets |
SELECT CustomerID,
CompanyName,
(SELECT AVG(Freight)
FROM Orders o
WHERE c.CustomerID = o.CustomerID) AS AvgFreight
FROM Customers c;
CustomerID | CompanyName | AvgFreight |
---|---|---|
ALFKI | Alfreds Futterkiste | 37.6 |
ANATR | Ana Trujillo Emparedados y helados | 24.4 |
ANTON | Antonio Moreno Taquería | 38.4 |
... | ... | ... |
Uncorrelated sub-query
SELECT CustomerID ,CompanyName FROM Customers WHERE CustomerID IN
(SELECT CustomerID FROM Orders WHERE Freight > 800);
WHERE
and FROM
Correlated sub-query
SELECT CustomerID, CompanyName,
(SELECT AVG(Freight) FROM Orders o WHERE c.CustomerID = o.CustomerID) AS AvgFreight
FROM Customers c;
WHERE
and SELECT
Correlated
Uncorrelated
Correlated sub-query
SELECT CustomerID,
CompanyName,
(SELECT AVG(Freight)
FROM Orders o
WHERE c.CustomerID = o.CustomerID) AS AvgFreight
FROM Customers c;
INNER JOIN
SELECT c.CustomerID,
c.CompanyName,
AVG(o.Freight)
FROM Customers c
INNER JOIN Orders o
ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID,
c.CompanyName;
Improving Query Performance in SQL Server