I have a query like this on Sql Server 2008:
DECLARE @START_DATE DATETIME
SET @START_DATE = GETDATE()
SELECT * FROM MY_TABLE
WHERE TRANSACTION_DATE_TIME > DATEADD(MINUTE, -1440, @START_DATE)
In the select query that you see above, does SqlServer optimize the query in order to not calculate the DATEADD result again and again. Or is it my own responsibility to store the DATEADD result on a temp variable?
Surprisingly, I’ve found that using GETDATE() inline seems to be more efficient than performing this type of calculation beforehand.
If you check the plans on those, the middle query will always come out with the lowest cost (but not always the lowest elapsed time). Of course it may depend on your indexes and data, and you should not make any assumptions based on one query that the same pre-emptive optimization will work on another query. My instinct would be to not perform any calculations inline, and instead use the
@sd2variation above… but I’ve learned that I can’t trust my instinct all the time and I can’t make general assumptions based on behavior I experience in particular scenarios.