How long between two dates
How long do orders take to ship? Subtract one date from another:
SELECT AVG(shipped_date - order_date) AS average_days
FROM orders
WHERE shipped_date IS NOT NULLIn DuckDB and PostgreSQL, one date minus another is a whole number of days. Orders that haven't
shipped have a NULL shipped_date, and the difference is NULL too, which AVG skips. Filtering
them out makes that clear to the next reader.
In other databases
SELECT shipped_date - order_date FROM ordersdate_diff('day', order_date, shipped_date) gives the same.
SELECT DATEDIFF(day, order_date, shipped_date) FROM ordersSELECT DATEDIFF(shipped_date, order_date) FROM ordersThe later date comes first, and it always counts days.
SELECT shipped_date - order_date FROM ordersSELECT DATE_DIFF(shipped_date, order_date, DAY) FROM orders