MySQL TIMEDIFF() Function
MySQL TIMEDIFF() Function
The MySQL TIMEDIFF() function calculates expr1 - expr2 and returns the elapsed duration as a TIME value. Positive results mean expr1 is later than expr2, while negative results start with a minus sign.
Teams use TIMEDIFF() to measure support ticket response times, checkout completion speed, or shift lengths within a few days.
Because TIMEDIFF() outputs a TIME type, it works well for short durations, though strict type-matching and range limits apply.
Syntax
TIMEDIFF(expr1, expr2)
expr1: ATIMEorDATETIMEexpression (the end time).expr2: ATIMEorDATETIMEexpression of the same type asexpr1(the start time).
Practical Example
In demo_orders, created_at records order placement and shipped_at records dispatch time (both DATETIME). You can measure fulfillment duration per order with TIMEDIFF().
SELECT
order_id,
created_at,
shipped_at,
TIMEDIFF(shipped_at, created_at) AS dispatch_duration
FROM demo_orders
WHERE order_id IN (401, 402, 403);
| order_id | created_at | shipped_at | dispatch_duration |
|---|---|---|---|
| 401 | 2026-05-10 09:00:00 | 2026-05-10 11:35:20 | 02:35:20 |
| 402 | 2026-05-09 22:00:00 | 2026-05-10 03:15:00 | 05:15:00 |
| 403 | 2026-05-10 14:00:00 | NULL | NULL |
Notice order 402 crosses midnight accurately, returning 05:15:00.
Common Mistakes & NULL Behavior
There are two critical rules every MySQL developer must remember about TIMEDIFF():
- Matching Types Required: Both
expr1andexpr2must beTIMEor both must beDATETIME. Passing oneTIMEand oneDATETIME(such asTIMEDIFF('2026-05-10 10:00:00', '09:00:00')) returnsNULL! - 838-Hour Clamping: MySQL
TIMEvalues span-838:59:59to838:59:59(about 34.95 days). Ifexpr1andexpr2are 60 days apart,TIMEDIFF()silently clamps the output to'838:59:59'with a truncation warning.
For spans exceeding 34 days, use TIMESTAMPDIFF(SECOND, start_dt, end_dt) instead of TIMEDIFF(). TIMEDIFF() also returns NULL whenever either input is NULL or invalid.
Frequently Asked Questions
Why did TIMEDIFF(NOW(), '08:00:00') return NULL?
NOW() returns a DATETIME, while '08:00:00' is a TIME. Wrap NOW() with TIME(NOW()) or convert '08:00:00' to a full DATETIME so both types match.
What is the difference between TIMEDIFF() and DATEDIFF()?
DATEDIFF() returns an integer count of days and ignores time components. TIMEDIFF() returns an exact TIME (hh:mm:ss) value within ±838:59:59.
How do I avoid the 838:59:59 limit for multi-month durations?
Use TIMESTAMPDIFF(HOUR, start_dt, end_dt) or TIMESTAMPDIFF(SECOND, start_dt, end_dt), which returns an unrestricted integer.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.