// dates & times reference

SQL DATEDIFF_BIG function

Counts unit boundaries between two datetimes like DATEDIFF, but returns a bigint for microsecond and nanosecond spans.

Categoría
Dates & times
Returns
bigint
In this category
71 of 121

Sintaxis

DATEDIFF_BIG(unit, startdate, enddate)

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Different name or syntax EXTRACT(EPOCH FROM b - a) never overflows
MySQL Not built in No built-in equivalent.
SQLite Different name or syntax JULIANDAY differences are floats
Oracle Not built in No built-in equivalent.

Ejemplos

SQL Server

SELECT DATEDIFF_BIG(MILLISECOND, '2026-01-01', '2026-03-01');  -- 5097600000

SQL Server

SELECT DATEDIFF_BIG(NANOSECOND, started, finished) FROM traces;

Conviene saberlo

  • DATEDIFF(MILLISECOND, ...) overflows int at about 24 days of span; DATEDIFF_BIG handles 292 million years of milliseconds.
  • It keeps DATEDIFF's semantics exactly: it counts boundaries, not elapsed units. DATEDIFF_BIG(YEAR, '2025-12-31', '2026-01-01') is still 1.
  • A bigint holds about 292 years of nanoseconds, so the inputs limit precision more than the result does: datetime stores 1/300-second ticks, and nanosecond diffs only mean something on datetime2.

Questions about DATEDIFF_BIG

When do I actually need DATEDIFF_BIG?

When the unit is small and the span is large: milliseconds beyond about 24.8 days, microseconds beyond about 35 minutes, nanoseconds beyond about 2.1 seconds. Plain DATEDIFF fails there with error 535 instead of wrapping.

Which SQL Server version added it?

SQL Server 2016. On older versions, diff in a coarser unit and scale it: DATEDIFF(SECOND, a, b) * CAST(1000 AS bigint) for approximate milliseconds.

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, PostgreSQL, SQLite.

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