Sql-server – Can somebody please tell what is the difference between these two date comparisons

datedate formatdatetimesql server

So I have 2 queries as follows:

f.DATE >= (GETDATE() - 3)

f.DATE >= CAST(CONVERT(VARCHAR(10),GETDATE() - 3,101) AS DATETIME)

I think they are the same but the second one gives me more rows than the first one does.
The data type of f.DATE is date though.

Can you please tell me where I get it wrong? Thank you much!!

Best Answer

The SQL Server GETDATE() function returns the exact date and time as it at the time of execution including the seconds/milisecond i.e. 2020-07-24 14:08:40.670. When the query executes, the

GETDATE()-3

evaluates the date/time as it at at the time of execution minus 3 days i.e. 2020-07-21 14:08:40.670 and thus only items with an f.Date greater then/equal to 2020-07-21 14:08:40.670 will be returned.

Using CONVERT with a Style of 101 on GETDATE() returns a date in the format of mm/dd/yyyy. In your example above of

CAST(CONVERT(VARCHAR(10),GETDATE() - 3,101) AS DATETIME)

the

CONVERT(VARCHAR(10),GETDATE() - 3,101)

evaluates the date/time as it at at the time of execution minus 3 days without any time portion i.e. 2020-07-21. When this is then CAST to a datetime the time portion is defaulted to 00:00:00 i.e. 2020-07-21 00:00:00.000.

As the derived expression in your second statement is earlier than that in the first you may have additional rows returned.