DATETRUNC (SQL Server 2022+) or CAST/CONVERT strips or rounds datetime values to the desired date part, removing the time component for cleaner grouping and comparison.
Truncating dates ensures consistent grouping, filtering, and joining by removing time fragments that cause duplicate buckets or missed matches.
SQL Server 2022+ offers DATETRUNC()
.Earlier versions rely on CAST()/CONVERT()
to the date
data type or DATEADD/DATEDIFF
tricks.
DATETRUNC(datepart, datetime_expression)
returns the datetime rounded down to the specified datepart
(year, quarter, month, week, day, hour, etc.).
SELECT DATETRUNC(month, order_date) AS order_month, COUNT(*) FROM Orders GROUP BY DATETRUNC(month, order_date);
Cast to date
when only the calendar date matters: CAST(order_date AS date)
.For month starts: DATEADD(day, 1-DAY(order_date), CAST(order_date AS date))
.
1) Prefer DATETRUNC
when available—simpler and SARGable. 2) Create computed, indexed columns if filtering on truncated values frequently. 3) Store dates without time when time is irrelevant.
Using non-SARGable expressions (e.g., CONVERT(varchar, order_date, 112)
) forces scans; stick to date types or DATETRUNC for index usage.
Yes—pass hour
or minute
as the datepart
.Example: DATETRUNC(hour, created_at)
buckets log data by hour.
No. It returns a computed value; source rows remain unchanged. Persist the result in a separate column if you need it stored.
.
Yes. Azure SQL Database runs on the latest SQL Server engine, so DATETRUNC is supported.
Not directly. DATETRUNC uses ISO or US calendar weeks depending on your DATEFIRST setting. Create a calendar table for custom fiscal periods.
Yes, but the function prevents direct index seek unless you add a computed persisted column with the truncated value and index that column.