Chapter 5 · Lesson 3 of 3
Date Arithmetic with DATE_DIFF
Calculate the number of days between two dates with DuckDB's DATE_DIFF, such as the shipping time between order and ship dates.
SQL can calculate the distance between two dates. In DuckDB, DATE_DIFF is a convenient way to do that.
SELECT order_id, DATE_DIFF('day', order_date, ship_date) AS days_to_ship
FROM ordersThis tells you how many days passed between each order and shipment.
Date arithmetic is useful for lead time, retention, overdue tasks, subscription length, and many other business questions.
Sample data
This lesson loads the orders table (7 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for orders
CREATE OR REPLACE TABLE orders (
order_id INTEGER,
customer_name VARCHAR,
order_date DATE,
ship_date DATE,
amount DECIMAL(10,2)
);
INSERT INTO orders VALUES
(1, 'Alice', '2024-01-03', '2024-01-05', 1200),
(2, 'Bob', '2024-01-15', '2024-01-20', 850),
(3, 'Charlie', '2024-02-01', '2024-02-04', 640),
(4, 'Diana', '2024-02-18', '2024-02-25', 430),
(5, 'Eve', '2024-03-02', '2024-03-03', 1500),
(6, 'Frank', '2024-03-28', '2024-04-02', 920),
(7, 'Grace', '2024-04-10', '2024-04-15', 760);Practice challenge
Return order_id and the number of shipping days as days_to_ship, ordered by order_id.
Hint: Use DATE_DIFF('day', order_date, ship_date) AS days_to_ship.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Working with Dates
Filter by date ranges, extract parts of dates, and calculate the days between two dates in DuckDB SQL.