// dates & times reference

SQL DATEDIFF function

Returns the amount of time between two dates. The name is shared by SQL Server and MySQL but the semantics are completely different, and the other engines subtract instead.

カテゴリ
Dates & times
Returns
integer
In this category
4 of 121

構文

DATEDIFF(day, start, end)  -- SQL Server
DATEDIFF(end, start)  -- MySQL, days

Each block is a separate form. The support table and the examples show which engine takes which.

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL Different name or syntax no DATEDIFF; date - date gives days, age() gives years, months and days
MySQL はい Supported under this name.
SQLite Different name or syntax no DATEDIFF; julianday(end) - julianday(start) gives days
Oracle Different name or syntax date - date gives days as a number; MONTHS_BETWEEN for months

例

SQL Server

SELECT DATEDIFF(day, order_date, ship_date) AS days_to_ship
FROM orders;

MySQL

SELECT DATEDIFF(ship_date, order_date) AS days_to_ship FROM orders;

PostgreSQL

SELECT ship_date - order_date AS days_to_ship FROM orders;

Oracle

SELECT ship_date - order_date AS days_to_ship FROM orders;

SQLite

SELECT julianday(ship_date) - julianday(order_date) AS days_to_ship
FROM orders;

知っておくと便利なこと

  • SQL Server's DATEDIFF counts unit boundaries crossed, not elapsed time: DATEDIFF(year, '2025-12-31', '2026-01-01') is 1.
  • MySQL's DATEDIFF only does whole days; TIMESTAMPDIFF(month, a, b) is the unit-aware version.
  • Argument order differs: SQL Server is (unit, start, end); MySQL is (end, start). Subtraction on PostgreSQL, SQLite and Oracle is end - start.
  • On PostgreSQL, date - date is an integer number of days, but timestamp - timestamp is an interval such as '2 days 03:00:00'. Use EXTRACT(epoch FROM b - a) for seconds.

Questions about DATEDIFF

Why does DATEDIFF(year, ...) say 1 for December 31 to January 1?

SQL Server counts boundaries crossed, not elapsed time. One year boundary lies between the two dates, so the answer is 1. For elapsed time, take DATEDIFF in a smaller unit (days, or seconds) and divide.

How do I get the difference in months?

SQL Server: DATEDIFF(month, a, b). MySQL: TIMESTAMPDIFF(month, a, b). PostgreSQL: date_part('year', age(b, a)) * 12 + date_part('month', age(b, a)). Oracle: MONTHS_BETWEEN(b, a).

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.