dateDiff returns the elapsed time between two Date/DateTime values in units like day, hour, or month.
dateDiff subtracts a start date from an end date and returns the integer count of the requested time unit (second, minute, hour, day, week, month, quarter, or year). It works with Date, Date32, and DateTime types.
Use dateDiff to measure customer latency—days between signup and first order, hours between order and shipping, or months between repeat purchases.These metrics uncover churn risk and growth opportunities.
Place the unit first, then the two date expressions: dateDiff('unit', start_date, end_date)
. ClickHouse returns a signed integer; negative results mean the end date precedes the start.
Yes.ClickHouse casts Date to midnight of that day when mixed with DateTime, letting you compare at any granularity.
The query below joins Customers
with their earliest Orders
and calculates the days waited before purchase.
SELECT c.id,
c.name,
dateDiff('day', c.created_at, MIN(o.order_date)) AS days_to_first_order
FROM Customers AS c
JOIN Orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;
"second", "minute", "hour", "day", "week", "month", "quarter", and "year" are valid.Capitalization is ignored.
Always index or use partition keys on the date columns you filter. Use consistent time zones—store in UTC and convert in the final SELECT to avoid off-by-one errors around DST changes.
Wrong: dateDiff(day, …)
. The unit must be a single-quoted string. Fix: dateDiff('day', …)
.
ClickHouse returns negative values if end_date < start_date
.Swap arguments or wrap the result in abs()
when you only need magnitude.
Complement dateDiff with dateAdd
for cohort tracking, toStartOfWeek
for grouping, and date_trunc
for bucketing time series.
.
No. dateDiff counts boundaries crossed. From 2023-01-01 to 2023-01-02 returns 1 day.
ClickHouse treats inputs as they are stored. For consistent results, store all timestamps in UTC or specify time zones explicitly.
Yes. Pass functions like NOW() or dateAdd() as start or end parameters to build dynamic date ranges.