I have a query that looks something like this
This takes 4 minutes to run and the execution path shows a complete table scan which took 3 minutes and 55 seconds then does a hash match partial aggregate which took 5 seconds.
Compare to this code
This takes less than one second to run and the execution path shows index seek on nonclustered index at a cost of 0, while doing RID Lookup on the table "cooltable" which took a millisecond.
Both queries are identical except for calculating first day of month. How can I force SQL to change the execution path so I can run the first query under 1 second?
Code:
-- sum up totals for each day starting with the first day of
-- current month midnight up to current day midnight
SELECT datetimestamp, SUM(total1) + SUM(total2) as totalsomething
FROM cooltable
WHERE total_type = 1
AND datetimestamp BETWEEN DATEADD(s,+1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
AND convert(varchar(12), getdate())
GROUP BY datetimestamp
This takes 4 minutes to run and the execution path shows a complete table scan which took 3 minutes and 55 seconds then does a hash match partial aggregate which took 5 seconds.
Compare to this code
Code:
-- sum up totals for each day starting with the first day of
-- current month midnight up to current day midnight
SELECT datetimestamp, SUM(total1) + SUM(total2) as totalsomething
FROM cooltable
WHERE total_type = 1
AND datetimestamp BETWEEN '2010-06-01'
AND convert(varchar(12), getdate())
GROUP BY datetimestamp
This takes less than one second to run and the execution path shows index seek on nonclustered index at a cost of 0, while doing RID Lookup on the table "cooltable" which took a millisecond.
Both queries are identical except for calculating first day of month. How can I force SQL to change the execution path so I can run the first query under 1 second?