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`.
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.
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`.
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
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
This example computes the difference in hours between two datetimes, resulting in 24 hours.
3. Usage with Table Data
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