Smart SQL Tools for Every Database

MySQL Function Reference

MySQL TIMESTAMPDIFF() Function

Learn how to use the MySQL TIMESTAMPDIFF date function with practical examples and cross-dialect alternatives.

Back to SQL Function Explorer

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

When to use it

Use TIMESTAMPDIFF for session duration, SLA response windows, aging calculations, and elapsed-time analytics.

Common mistakes

Troubleshoot MySQL TIMESTAMPDIFF problems

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.