MySQL Function Reference
MySQL TIMESTAMPDIFF() Function
Learn how to use the MySQL TIMESTAMPDIFF date function with practical examples and cross-dialect alternatives.
Syntax
TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)
TIMESTAMPDIFF returns the integer difference between two datetime values in the requested unit.
Basic Example
SELECT TIMESTAMPDIFF(DAY, '2026-05-10', '2026-05-17') AS days_between;
-- Result: 7
Practical query example
SELECT session_id,
TIMESTAMPDIFF(MINUTE, login_at, logout_at) AS session_minutes
FROM user_sessions;
Commonly used units
YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
TIMESTAMPDIFF vs DATEDIFF
- Use DATEDIFF for day-level date comparisons.
- Use TIMESTAMPDIFF for hour/minute/second precision and explicit unit control.
When to use it
Use TIMESTAMPDIFF for session duration, SLA response windows, aging calculations, and elapsed-time analytics.
Common mistakes
- Forgetting the first
unitargument. - Reversing datetime arguments and getting negative results unexpectedly.
- Expecting decimals. TIMESTAMPDIFF returns whole integers in the selected unit.
Related SQL Functions
FAQ
Why is TIMESTAMPDIFF negative?
The function computes datetime_expr2 - datetime_expr1 in the unit you provide. Swap arguments if needed.
Does TIMESTAMPDIFF return fractional values?
No. It returns whole integers in the requested unit.
Can TIMESTAMPDIFF be used in WHERE clauses?
Yes, but test index-friendly alternatives for large tables if performance becomes a concern.