Improving Query Performance in SQL Server
Dean Smith
Founder, Atamai Analytics
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations
WHERE Capital IN
(SELECT CityName
FROM Cities)
AND Capital IN
(SELECT CityName
FROM Cities
WHERE Pop2017 > 1000000);
STATISTICS TIME
- command reports number of milliseconds, required to parse, compile, and execute a query.
SQL Server parse and compile time:
CPU time = 16 ms, elapsed time = 21 ms.
(88 rows affected)
SQL Server Execution Times:
CPU time = 390 ms, elapsed time = 382 ms.
SQL Server Execution Times:
CPU time = 390 ms, elapsed time = 382 ms.
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations
WHERE Capital IN
(SELECT CityName -- 1st sub-query
FROM Cities)
AND Capital IN
(SELECT CityName -- 2nd sub-query
FROM Cities
WHERE Pop2017 > 1000000);
SET STATISTICS TIME ON
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations
WHERE Capital IN
(SELECT CityName -- 1st sub-query
FROM Cities)
AND Capital IN
(SELECT CityName -- 2nd sub-query
FROM Cities
WHERE Pop2017 > 1000000);
SQL Server Execution Times:
CPU time = 391 ms, elapsed time = 381 ms.
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations n
WHERE EXISTS
(SELECT 1
FROM Cities c
WHERE n.Capital = c.CityName
AND Pop2017 > 1000000);
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations n
WHERE EXISTS
(SELECT 1
FROM Cities c
WHERE n.Capital = c.CityName
AND Pop2017 > 1000000);
SET STATISTICS TIME OFF
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations
WHERE Capital IN
(SELECT CityName
FROM Cities)
AND Capital IN
(SELECT CityName
FROM Cities
WHERE Pop2017 > 1000000);
SQL Server Execution Times:
CPU time = 391 ms, elapsed time = 381 ms.
EXISTS
SELECT UNStatisticalRegion,
CountryName,
Capital
FROM Nations n
WHERE EXISTS
(SELECT 1
FROM Cities c
WHERE n.Capital = c.CityName
AND Pop2017 > 1000000);
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
Elapsed time
CPU time
elapsed time = 2032 ms.
elapsed time = 2060 ms.
elapsed time = 1915 ms.
elapsed time = 4009 ms.
elapsed time = 3511 ms.
Average elapsed time = 2705 ms.
Improving Query Performance in SQL Server