The first query is:
declare @myDate datetime = DATEADD(D,-2000,getdate())
SELECT * FROM [myTable]
where CreatedDate >= @myDate
The second query is:
SELECT * FROM [myTable]
where CreatedDate >= DATEADD(D,-2000,getdate())
I expect that the first query may be faster, because of ‘dateadd’ function calculates once. But in practice this queries are both equal (2 seconds, 30 000 rows)
getdate()is a runtime constant function and is only evaluated once per function reference which is whywill return the same result for all rows regardless of how long the query takes to run.
There is a difference between the two however. As the first one uses a variable and the plan is compiled before the variable is assigned to SQL Server will (in the absence of a recompile) assume that 30% of the rows will be returned. This guess may cause it to use a different plan than the second query.
Something to bear in mind with using
GETDATE()directly in a filter is that it evaluatesGETDATE()at compile time and thereafter it is possible for the selectivity to change dramatically without either the query or the data changing to trigger a recompile. In the example below against a 1,000 row table the query using a variable leads to a plan with an estimated 300 rows and a full table scan whereas the query with the function call embedded estimates 1 row and does a bookmark lookup. This is accurate on the first run but on the second run due to the passage of time now all rows qualify and it ends up doing 1,000 such random lookups.