DATEDIFF() returns the number of whole days between two DATE or DATETIME values.
Use DATEDIFF(date1, date2)
. MySQL subtracts date2
from date1
and returns the signed count of days. Positive means date1
is later.
Syntax is simple: DATEDIFF(expr1, expr2)
. Both expressions must resolve to DATE, DATETIME, or TIMESTAMP. The function ignores any time component.
Use DATE, DATETIME, TIMESTAMP columns, or string literals convertible to dates (e.g., '2024-01-15'). Mixing types is allowed but can slow queries through implicit casts.
Join Customers
and Orders
, take the earliest order_date
, then apply DATEDIFF
against created_at
.
SELECT c.id,
c.name,
MIN(o.order_date) AS first_order_date,
DATEDIFF(MIN(o.order_date), c.created_at) AS days_to_first_order
FROM Customers c
JOIN Orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;
Store dates in UTC, index date columns used in filters, and always place the later date first to avoid negative results unless that sign matters.
Argument order errors flip the sign. Relying on VARCHAR dates forces conversions and blocks index use, slowing scans.
No. DATEDIFF works only with whole days. Use TIMESTAMPDIFF for smaller units.
The function compares the raw stored values. Store dates in UTC to avoid cross-zone confusion.
Yes, given identical inputs it always returns the same integer. It is safe for generated columns and deterministic functions.