The expense is using the DateAdd function not only in the SELECT, but also in the WHERE;
Or using the Sub Query which initially returns more data than I need, but then can be filtered without using the DateAdd function again on the database.
Execution Plan seems to imply that they are identical as far as it is concerned.
I’m wondering which would be more efficient?
DECLARE @DateFrom DateTime
SET @DateFrom = '2011-05-27'
DECLARE @DateTo DateTime
SET @DateTo = '2011-06-27'
SELECT id, name,
dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
FROM tablename
WHERE dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM'))
BETWEEN @DateFrom AND @DateTo
ORDER BY itsm_requiredbyx desc
---------------------------------------------------------------------------------------------
SELECT *
FROM
(
select id, name,
dateAdd(hour, datediff(hour, getdate(), getutcdate()), --UTC offset
dateadd(second, itsm_requiredbyx, '1/1/1970 12:00 AM')) as itsm_requiredbyx
from tablename
) RR
WHERE itsm_requiredbyx BETWEEN @DateFrom AND @DateTo
ORDER BY itsm_requiredbyx desc
I don’t think it matters which of the two you use. And the Execution Plans agree.
But it seems you are doing calculations to column
itsm_requiredbyxand then check if the result is between two external values,@DateFromand@DateTo. This way, all datetimes from this field are processed by the functions before theWHEREconditions can be applied and no index can be used. The second link (Ten Common SQL Programming Mistakes) in @DOK’s answer provide more detailed info on why and when this happens.If you don’t do any calculations to the column, but you do the (reversed) calculations to the external values instead and then check if
itsm_requiredbyxis between these two calculated values, the query can use an index ofitsm_requiredbyx(and the functions will only be called twice and not for every row in the table).