Sunday, December 22, 2024

MySQL TIMEDIFF() Function

 The TIMEDIFF() function in MySQL is used to calculate the difference between two time or datetime expressions. It returns the difference as a TIME value.

Syntax:

TIMEDIFF(time1, time2)
  • time1: The first time/datetime value.
  • time2: The second time/datetime value.

Return Value:

The return value is the difference between time1 and time2 in the format HH:MM:SS. If time1 is greater than time2, the result will be positive; otherwise, it will be negative.

Example Usage:

  1. Simple Time Difference:
SELECT TIMEDIFF('2024-12-23 14:30:00', '2024-12-23 13:15:00');

Output: 01:15:00 (1 hour and 15 minutes)

  1. Time Difference with Only Time:
SELECT TIMEDIFF('14:30:00', '13:15:00');

Output: 01:15:00 (1 hour and 15 minutes)

  1. Negative Time Difference:
SELECT TIMEDIFF('12:00:00', '14:00:00');

Output: -02:00:00 (2 hours negative)

  1. Using TIMEDIFF() in a Query:
SELECT name, TIMEDIFF(end_time, start_time) AS duration
FROM events;

This will calculate the time difference between end_time and start_time for each event and display it as duration.

Notes:

  • If you use DATETIME or TIMESTAMP values, the TIMEDIFF() function only considers the time part and ignores the date portion.
  • TIMEDIFF() only works with values of the TIME, DATETIME, or TIMESTAMP data types.

Let me know if you'd like more specific examples or explanations!

No comments:

Post a Comment