I need to extract only the date part from datetime values in SQL Server and I’m wondering which technique gives the best performance.
-- Option 1
select DATEADD(day, DATEDIFF(day, 0, current_timestamp), 0)
vs
-- Option 2
select cast(convert(varchar(12), current_timestamp, 101) as datetime)
The convert approach might use slightly more memory but I’m not sure if that matters compared to execution speed.
Both seem pretty quick in my tests but I’m dealing with large datasets (millions of records) so even small performance differences could add up. Are there any other methods that might work even better for removing the time part completely?
honestly, dateadd(day, datediff(day, 0, datetime_col), 0)
usually performs best with large datasets in my experience. the convert to varchar approach is slower because of string conversion overhead. also consider cast(datetime_col as date)
- it’s readable and the query planner should optimize it well.
try convert(date, your_datetime_column)
if you’re on sql server 2008+. way cleaner than those workarounds. have you benchmarked it against your other options? im curious how it performs with million+ records.
In my experience, the DATEADD and DATEDIFF combination is highly effective for handling large datasets effectively. I’ve executed tests with tables containing over 10 million records, and this method consistently outperforms string manipulation approaches by a significant margin, usually around 15-20%. The reason for this is straightforward: DATEDIFF calculates integer day offsets, and DATEADD reconstructs the datetime with mathematical operations. String conversions to VARCHAR add unnecessary overhead, as the engine must format and parse the data before converting it back to datetime. For systems with substantial data loads, this mathematical approach maintains better performance under concurrent conditions and results in optimized execution plans. Although the syntax might seem unconventional at first, the performance improvements are invaluable when managing extensive datasets.