TSQL datetimes functions in where clause

2019-07-27 22:41发布

问题:

I have to make a query to a table of a database that is hosted in a MSSQL server.

The query is the following:

select *
from tableA
where createdOn between @startDate and @endDate

The type of variables @startDate and @endDate is datetime. If @endDate is equal to the current date and @startDate is equal to the date once month before, I thought that we could make the query either as

declare @startDate datetime
declare @endDate datetime

set @startDate = DATEADD(month,-1,GETDATE())
set @endDate = GETDATE()


select *
from tableA
where createdOn between @startDate and @endDate

or as

select *
from tableA
where createdOn between DATEADD(month,-1,GETDATE()) and GETDATE()

I thought that the first query would be faster that the second, because in the second query we call the functions in the where clause. I wrote both versions of my query and I executed them also. However, I didn't notice any significant difference in the performance.

Could someone explain me why I didn't see any change. Maybe the thought that the first query should be faster that the second was false. Please let me know, id that's the case, why is wrong.

Thanks in advance for any help.

回答1:

The Query Optimiser.

The query optimiser made both queries the same. It knows that GETDATE() is the same for all tests so optimises the call away.

Read here: Query Optimiser Deep Dive and Query Optimiser for way more info than you'd ever want :-)