They are not equivalent. Records that are 7 days ago, but before the current time of day - will only be returned in query #2:
When comparing days using the DATEADD
function, it does not take the time part into consideration. The function will return 1 when comparing Sunday & Monday, regardless of the times.
Demo:
DECLARE @MyTable TABLE(pk INT, LogInsertTime DATETIME);
INSERT @MyTable
VALUES (1, DATEADD(HOUR, 1, CAST(DATEADD(DAY, -7, CAST (GETDATE() AS DATE))AS DATETIME))),
(2, DATEADD(HOUR, 23, CAST(DATEADD(DAY, -7, CAST (GETDATE() AS DATE)) AS DATETIME)));
DECLARE @DateTime DATETIME = GETDATE();
SELECT *
FROM @MyTable
WHERE DATEDIFF(DAY, LogInsertTime, @DateTime) > 7;
-- 0 records.
SELECT *
FROM @MyTable
WHERE LogInsertTime < @DateTime - 7;
-- 1 record.
The logical equivalent of the first query that will enable potential index usage is to either remove the time part of @DateTime
or to set the time to 0:00:00
:
SELECT *
FROM @MyTable
WHERE LogInsertTime < CAST(@DateTime - 7 AS DATE);
The reason why the first query cannot use a index on LogInsertTime
is because the column is buried within a function. Query #2 compares the column to a constant value which enables the optimizer to choose a index on LogInsertTime
.
LogInsertTime
is?