MySQL TIMEDIFF() Function

The TIMEDIFF() function in MySQL calculates the difference between two time or datetime values. This is a very useful function for working with time intervals and for performing time-based analysis or calculations within your MySQL queries.



TIMEDIFF(): Definition and Usage

TIMEDIFF() takes two time or datetime values as input and returns the difference between them as a time value (in HH:MM:SS format). The order of the arguments is important: the difference is calculated as time1 - time2. The time values should be in a consistent format. If the input is not a valid time or datetime, or if either input is `NULL`, the function returns `NULL`.

Syntax

Syntax

TIMEDIFF(time1, time2)
      

Parameter Values

Parameter Description
time1 The first time or datetime value. This is required.
time2 The second time or datetime value. This is required.

Examples

Calculating the Difference Between Two Times

This example calculates the difference between two time values.

Syntax

SELECT TIMEDIFF("13:10:11", "13:10:10");
      
Output

00:00:01
      

Calculating the Difference Between Two Datetimes

This example shows calculating the difference between two datetime values. Note that only the time portion is considered.

Syntax

SELECT TIMEDIFF("2017-06-25 13:10:11", "2017-06-15 13:10:10");
      
Output

00:00:01
      

**Note:** The output of `TIMEDIFF()` is a time value in 'HH:MM:SS' format. If the result is negative, it means that `time2` is after `time1`. The date portion of datetime values is ignored in the calculation. If the inputs are not valid time or datetime values, or if either input is NULL, the result will be `NULL`.