How to compare datetime with only date in SQL Server
To compare dates in SQL Server, transform the datetime
to a date
using the CAST
function:
This approach excludes the time component and enables a pure date comparison.
SARGable vs. Non-SARGable: The Efficiency Choice
A SARGable approach raises the efficiency of indexing and querying. Using functions like CONVERT()
on datetime columns turn queries non-SARGable. Instead, use a range comparison with >=
and <
:
-- Yes, it's like asking if your salary is >=
lowest desired and <
ridiculously high. We keep our hopes high!
The Full 24: Range comparison Strategy
In SQL Server, comparing datetime
values is more than just the date. It's about the ensuing 24 hours, down to the millisecond. To capture an entire day, use range comparisons:
-- Yes, in SQL Server land, a day ends at 23:59:59.997
. Not at midnight, apparently!
The Old Chap's Rule: Prior SQL Server 2008
Before 2008, SQL Server had no DATE
. So, the old chap had to convert datetime
to varchar
and back:
-- Yes, the SQL equivalent of taking a car apart and putting it back together again just to paint it!
The BETWEEN Pitfall
A datetime
comparison using BETWEEN
can be misleading due to the inclusion of the end value’s time stamp. Handcraft your date ranges to avoid confounding results:
-- It's BETWEEN
rock and a hard place, but you've got this!
The Here and Now: Getting Current Date
GETDATE()
is a built-in function that gives you the current system date and time. Remember to cast it to a DATE
for a comparison for today's date:
-- Yes, we're time travelers checking if DateTimeColumn
exists any time during today!
Was this article helpful?