// dates & times reference

SQL TIMESTAMPDIFF function

Returns the whole number of named units between two datetimes, truncating any remainder.

Catégorie
Dates & times
Returns
integer
In this category
70 of 121

Syntaxe

TIMESTAMPDIFF(unit, datetime1, datetime2)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax DATEDIFF(unit, a, b); same order, but boundary-crossing semantics
PostgreSQL Different name or syntax EXTRACT(EPOCH FROM b - a) / 86400 or AGE-based month math
MySQL Oui Supported under this name.
SQLite Different name or syntax CAST((JULIANDAY(b) - JULIANDAY(a)) AS INTEGER) for days
Oracle Different name or syntax b - a for days; MONTHS_BETWEEN for months

Exemples

MySQL

SELECT TIMESTAMPDIFF(MONTH, '2026-01-15', '2026-08-01');  -- 6

MySQL

SELECT TIMESTAMPDIFF(MINUTE, started_at, ended_at) FROM jobs;

SQL Server

SELECT DATEDIFF(MONTH, '2026-01-15', '2026-08-01');  -- 7 (boundary count)

Bon à savoir

  • Argument order matters: TIMESTAMPDIFF(MONTH, earlier, later) is positive; swapping them gives a negative.
  • The result is truncated, never rounded: TIMESTAMPDIFF(HOUR, '2026-01-01 10:00', '2026-01-01 10:59') returns 0.
  • SQL Server's DATEDIFF counts unit boundaries crossed, so DATEDIFF(YEAR, '2025-12-31', '2026-01-01') is 1; TIMESTAMPDIFF(YEAR, ...) returns 0. MySQL's DATEDIFF, meanwhile, only does days.

Questions about TIMESTAMPDIFF

Why does DATEDIFF give 7 months when TIMESTAMPDIFF gives 6?

SQL Server's DATEDIFF counts how many month boundaries you crossed; TIMESTAMPDIFF computes complete months elapsed. For tenure-style answers, TIMESTAMPDIFF's semantics are usually what you want.

How do I get fractional months?

Oracle's MONTHS_BETWEEN(b, a) returns decimal months. MySQL has no fractional form; TIMESTAMPDIFF(DAY, a, b) / 30.4375 is an average-month approximation, not a calendar answer.

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, MySQL, SQLite, Oracle.

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