MySQL TIMEDIFF() Function

MySQL TIMEDIFF() fucntion; Through this tutorial, i am going to show you how to get the difference between two datetime in the mysql using timediff() function with the help of examples.

MySQL TIMEDIFF() Function

The MySQL TIMEDIFF function returns the difference (expressed as a time value) between two time/datetime values

Syntax of MySQL TIMEDIFF() Function

Syntax of the MySQL TIMEDIFF() function; as follows:

TIMEDIFF(agr1,agr2)

Here, agr1 and agr2 are the two values to compare. The return value is agr2 subtracted from agr1 .

Example 1 – MySQL TIMEDIFF() Function

Let’s take the first simple and basic example of this function; as follows:

SELECT TIMEDIFF('09:45:35', '07:15:15');

Output-1

+----------------------------------+
| TIMEDIFF('09:45:35', '07:15:15') |
+----------------------------------+
|  02:30:20                        |
+----------------------------------+

Example 2 – MySQL TIMEDIFF() Function

The time value can represent the time elapsed, so it is not limited to less than 24 hours; as follows:

SELECT TIMEDIFF('350:40:10', '11:35:25');

Output-2

+-----------------------------------+
| TIMEDIFF('350:40:10', '11:35:25') |
+-----------------------------------+
|  339:04:45                        |
+-----------------------------------+

Example 3 – MySQL TIMEDIFF() Function

Let’s take an example using the mysql timediff() function with second value is larger than first value, you will get a negative value for the difference in time. It is completely legitimate; as follows:

SELECT TIMEDIFF('10:35:25', '350:40:10');

Output-3

+-----------------------------------+
| TIMEDIFF('10:35:25', '350:40:10') |
+-----------------------------------+
|  -339:04:45                       |
+-----------------------------------+

Example 4 – MySQL TIMEDIFF() Function

Let’s an take another example of MySQL timediff() function with DateTime values; as follows:

SELECT TIMEDIFF('2020-04-01 11:45:25', '2020-02-01 11:25:25');

Output-4

+--------------------------------------------------------+
| TIMEDIFF('2020-04-01 11:45:25', '2020-02-01 11:25:25') |
+--------------------------------------------------------+
| 838:59:59                                              |
+--------------------------------------------------------+

Note: that both the arguments must be of the same type.

Conclusion

MySQL TIMEDIFF() Function, you have learned how to use MySQL timediff() function with various examples.

Leave a Comment