// dates & times reference

SQL DATEADD DATEDIFF truncation trick

Counts units from a base date and re-adds them, flooring the timestamp: the classic SQL Server truncation before DATETRUNC existed.

Categoría
Dates & times
Returns
datetime
In this category
92 of 121

Sintaxis

DATEADD(unit, DATEDIFF(unit, 0, date), 0)

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Not built in No built-in equivalent.
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

Ejemplos

SQL Server

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, order_date), 0) AS day_only FROM orders;

SQL Server

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, order_date), 0) AS month_start FROM orders;

SQL Server

SELECT DATETRUNC(DAY, order_date) FROM orders;  -- 2022+ spelling

Conviene saberlo

  • It works because 0 is SQL Server's epoch date 1900-01-01: DATEDIFF counts midnights since then, DATEADD walks them back; the remainder is discarded, i.e. truncation.
  • The month form DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) truncates to the month; QUARTER and YEAR work the same way.
  • The result is always datetime, because the 0 is read as a datetime, so datetime2 inputs lose their extra precision. Small units overflow: DATEDIFF(SECOND, 0, GETDATE()) exceeds int and fails with error 535.
  • The WEEK form ignores DATEFIRST and returns Mondays (1900-01-01 was a Monday), but DATEDIFF(WEEK) counts Sunday boundaries, so a Sunday rounds forward: 2026-08-02 becomes 2026-08-03.

Questions about DATEADD/DATEDIFF trick

Why does the trick use 0 instead of '1900-01-01'?

0 casts to the datetime epoch automatically; it is shorter and avoids string parsing. Same value, same result.

Should I keep using it in new code?

On SQL Server 2022+ use DATETRUNC: clearer, and it handles week starts via DATEFIRST without off-by-one corrections.

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

Cheat sheets for the engines that have it: SQL Server.

// 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.