SQL Date Math and Lead Times
Subtracting dates answers real questions: how long did shipping take, how old is this record?
Dates aren't just for filtering. The distance between two of them is often the number you actually want: lead time, age, time-to-resolve.
DuckDB's
date_diff('day', start, end)
returns the whole number of days from one date to another. The first
argument is the unit, so you can switch to
'month'
or
'year'. Those count calendar boundaries crossed rather than full periods, so
January 31 to February 1 is one month. (Other databases spell this
DATEDIFF
or just subtract the dates.)
select ticket_id,
date_diff('day', opened_at, closed_at) as days_open
from tickets
where closed_at is not null Schema · Garden Shop Table · orders 6 columns · 24 rows
One row per order. Unshipped orders have a null shipped_date.
For every shipped order, show how long fulfillment took.
Return order_id, order_date,
shipped_date, and the number of days between them as
days_to_ship. Exclude orders that haven't shipped, and show the
slowest first, breaking ties by order id.
Run your query to inspect the result.
Expected answer
- Columns: order_id, order_date, shipped_date, days_to_ship.
- Rows: 17 shipped orders (the 7 unshipped ones are excluded).
- days_to_ship is the gap from order_date to shipped_date, mostly 2-3 days.
Related
Date parts, math, and truncation.
Everyday date and text functions.
Practice safe date filters, buckets, and lead-time reports.
Use a half-open range, not BETWEEN, on timestamps.
Length, case, trimming, slicing, and concatenation.
Debug filters that match nothing.