MySQL DATEDIFF() Function
The DATEDIFF()
function in MySQL calculates the difference in days between two date values. It returns the number of days from the first date to the second date.
Syntax
Parameters:
end_date
: The later date.start_date
: The earlier date.
Return Value:
- Returns an integer representing the number of days between the two dates.
- A positive value if
end_date
is afterstart_date
. - A negative value if
end_date
is beforestart_date
. - Returns
NULL
if either date isNULL
.
Examples
1. Basic Usage
Output:
2. When the Start Date is After the End Date
Output:
Here, the result is negative because the start date is after the end date.
3. Using DATEDIFF on Table Data
Assume we have an orders
table:
This query calculates the number of days between order_date
and delivery_date
.
4. Using DATEDIFF in a WHERE Clause
Find all orders that took more than 7 days to deliver:
Handling NULL and Invalid Dates
Key Notes:
- Only works with
DATE
,DATETIME
, orTIMESTAMP
values. - Ignores time parts; only counts full days.
- If you need precise differences including time, use
TIMESTAMPDIFF()
instead.
Alternative: Getting Difference in Other Units
If you need differences in hours, minutes, or seconds, use:
Output: 26
(26 hours difference).
Conclusion
DATEDIFF()
calculates the number of days between two dates.- Ignores time components and returns an integer.
- Useful for tracking date differences in orders, projects, and event logs.
A handy function for date-based calculations in MySQL! š