DATEDIFF and TIMESTAMPDIFF return the number of days or custom time units between two dates in MariaDB.
DATEDIFF(start_date,end_date) returns the integer count of days from start_date to end_date. Negative values mean end_date precedes start_date. Use it for quick day-level gaps, such as customer lifetime or shipping delays.
TIMESTAMPDIFF(unit,start_date,end_date) lets you measure gaps in SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR. Choose it when you need granular control, like hours until an order ships or months since customer signup.
Join Orders to itself or another table, then call DATEDIFF(o2.order_date,o1.order_date). Alias the result as days_between to improve readability and reuse in reporting views.
Yes. TIMESTAMPDIFF(MONTH,c.created_at,o.order_date) computes whole months. Combine with MIN(o.order_date) per customer to capture the first purchase accurately.
See the full syntax section below for parameter order, supported units, and null behavior. Copy-paste the ecommerce examples to test in your Galaxy SQL editor.
Cast strings to DATE before comparison, index date columns for speed, and always specify an alias. Wrap complex logic in a CTE to keep the main SELECT clean and maintainable.
Remember DATEDIFF counts full midnight boundaries. Add 1 day if your business logic treats the start date as an active day (e.g., hotel nights). Use TIMESTAMPDIFF for exact hours or minutes.
See the end of the article for frequent pitfalls like parameter order mix-ups and mismatched data types, plus quick solutions.
Scroll to the FAQ section for answers on performance, timezone handling, and partial month calculations.
No. DATEDIFF and TIMESTAMPDIFF work on native date/time values without timezone conversion. Convert to UTC before storing for consistent results.
Both are lightweight functions. Performance depends on indexed date columns and query plan, not the function itself.
Add 1 to the DATEDIFF result or use TIMESTAMPDIFF with HOUR and divide/round as needed to match business rules.