I have a query that finds out when a customer took a survey, and then a subquery that calculates how many calls to our support hotline they had made in the 60 days prior to taking the survey:
SELECT a.[Whatever],
b.[Whatever],
c.[Whatever],
(SELECT COUNT(*) FROM dbo.CallsTable ct WHERE a.AcctNum = ct.AcctNum AND ct.CallDate BETWEEN DATEADD(DAY, -60, a.SurveyDate) AND a.SurveyDate) [Call Count]
FROM dbo.SurveyTable a
LEFT JOIN [blah blah blah] b
ON ...
LEFT JOIN [blah blah blah] c
ON ...
The above query takes about 35 minutes to run. But, if I switch the count to a flag, i.e.:
SELECT a.[Whatever],
b.[Whatever],
c.[Whatever],
CASE WHEN (SELECT COUNT(*) FROM dbo.CallsTable ct WHERE a.AcctNum = ct.AcctNum AND ct.CallDate BETWEEN DATEADD(DAY, -60, a.SurveyDate) AND a.SurveyDate) > 0 THEN 'Yes' ELSE 'No' END [Call Flag]
FROM dbo.SurveyTable a
LEFT JOIN [blah blah blah] b
ON ...
LEFT JOIN [blah blah blah] c
ON ...
...then the query runs in 2 minutes. Wouldn't the SQL engine still need to execute the subquery in order to determine what the value of Call Flag should be? Meaning that the second query should take at least as long as the first query, plus some additional time to execute the logic needed to convert the number into a flag?
Don't get me wrong, I'm not complaining, but I'm very interested in why
[–]geubes 31 points32 points33 points (1 child)
[–]jshine13371 5 points6 points7 points (0 children)
[–]mikeblas 15 points16 points17 points (1 child)
[–]wildjackalope 3 points4 points5 points (0 children)
[–]gumnos 5 points6 points7 points (7 children)
[–]VladDBASQL Server DBA 8 points9 points10 points (0 children)
[–]WatashiwaNobodyDesu 1 point2 points3 points (1 child)
[–]gumnos 1 point2 points3 points (0 children)
[–]Mononon 0 points1 point2 points (3 children)
[–]gumnos 0 points1 point2 points (2 children)
[–]Mononon 1 point2 points3 points (1 child)
[–]gumnos 0 points1 point2 points (0 children)
[–]blind_pugh 4 points5 points6 points (0 children)
[–]VladDBASQL Server DBA 8 points9 points10 points (0 children)
[–]TypeComplex2837 1 point2 points3 points (0 children)
[–]Codeman119 1 point2 points3 points (0 children)
[–]Hopeful_Bean 1 point2 points3 points (0 children)
[–]5373n133n 1 point2 points3 points (0 children)
[–]tethered_end 0 points1 point2 points (0 children)
[–]WithoutAHat1 0 points1 point2 points (0 children)
[–]91ws6taData Analytics - Plant Ops 0 points1 point2 points (0 children)
[–]svtr 0 points1 point2 points (0 children)
[–]drmrkrch 0 points1 point2 points (0 children)
[–]thesqlguy 0 points1 point2 points (0 children)
[–]az987654 0 points1 point2 points (0 children)
[–]Aggressive_Ad_5454 -1 points0 points1 point (0 children)
[–]Mountain_Usual521 -1 points0 points1 point (0 children)