// dates & times reference

SQL DATETRUNC function

Floors a date/time to the start of the named unit, the native answer to SQL Server's pre-2022 DATEADD/DATEDIFF truncation trick.

类别
Dates & times
Returns
same type as input (datetime2 family)
In this category
85 of 121

语法

DATETRUNC(datepart, date)

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL Different name or syntax date_trunc('day', d); same capability, different name
MySQL Different name or syntax DATE(d) for days, DATE_FORMAT(d, '%Y-%m-01') for months; no native truncate
SQLite Different name or syntax strftime + date(); see the bucketing page
Oracle Different name or syntax TRUNC(d, 'DD')

示例

SQL Server

SELECT DATETRUNC(MONTH, '2026-08-15 14:30');  -- 2026-08-01 00:00:00.0000000

SQL Server

SELECT DATETRUNC(WEEK, order_date) AS week_start, COUNT(*) FROM orders GROUP BY DATETRUNC(WEEK, order_date);

PostgreSQL

SELECT date_trunc('day', TIMESTAMP '2026-08-15 14:30');

值得了解

  • Requires SQL Server 2022 or Azure SQL; on older instances the DATEADD(DAY, DATEDIFF(DAY, 0, d), 0) idiom is the standard substitute.
  • DATETRUNC(week, d) starts weeks on the day set by SET DATEFIRST (default Sunday), so it does not match ISO Monday weeks unless you change DATEFIRST or compute by hand.
  • The result keeps the input type: a datetime2(3) comes back as datetime2(3), and a string literal becomes datetime2(7). A date input rejects units below DAY: DATETRUNC(HOUR, a date) raises error 9810.

Questions about DATETRUNC

How do I truncate on SQL Server 2019?

The idiom: DATEADD(DAY, DATEDIFF(DAY, 0, d), 0) for days, DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) for months. Or upgrade: DATETRUNC replaces all of it.

Is DATETRUNC the same as PostgreSQL's date_trunc?

Semantics yes, spelling no: SQL Server takes bare datepart keywords ('MONTH'), PostgreSQL takes quoted strings ('month') and also offers date_bin for fixed grids.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.