Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL TIMESTAMPDIFF() Function

The `TIMESTAMPDIFF()` function in MySQL calculates the difference between two date or datetime expressions. It returns the result in the specified unit, such as seconds, minutes, hours, days, or years.

Usage

The function is used to determine the time interval between two dates in a chosen unit, making it ideal for age calculations, duration measurements, and any temporal analysis. It takes three arguments: the unit of measurement, the starting timestamp, and the ending timestamp. The function returns an integer representing the difference in the specified unit. The difference is calculated as the number of unit boundaries crossed from `datetime_expr1` to `datetime_expr2`.

sql
TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)

In this syntax, `unit` specifies the result's time unit (e.g., SECOND, MINUTE, HOUR), `datetime_expr1` is the starting datetime, and `datetime_expr2` is the ending datetime.

Examples

1. Basic Days Difference

sql
SELECT TIMESTAMPDIFF(DAY, '2023-01-01', '2023-01-10') AS days_difference;

This example calculates the number of days between January 1, 2023, and January 10, 2023, returning a result of 9.

2. Calculating Hours Between Two DateTimes

sql
SELECT TIMESTAMPDIFF(HOUR, '2023-01-01 08:00:00', '2023-01-02 08:00:00') AS hours_difference;

This example computes the difference in hours between two datetimes, resulting in 24 hours.

3. Usage with Table Data

sql
SELECT order_id, TIMESTAMPDIFF(MINUTE, order_time, delivery_time) AS delivery_duration
FROM orders;

In this example, the `TIMESTAMPDIFF()` function calculates the delivery duration in minutes for each order, pulling data from the `orders` table.

Tips and Best Practices

  • Choose the correct unit. Ensure the unit of measurement fits the context of your query to avoid misleading results.
  • Understand datetime formats. Use compatible datetime formats for accurate calculations.
  • Leverage indexes. If analyzing large datasets, ensure the datetime columns are indexed to improve performance.
  • Handle NULL values. Consider potential NULL datetime values and handle them appropriately to prevent errors.
  • Consider edge cases. Be aware of scenarios where the end date is earlier than the start date, as this may affect the result.