Lessons › SQL › Chapter 4: Shaping data
SQL lesson
Date difference functions
Take one date from another to get the days between them. ship_date - order_date gives how long an order took to ship. Put the later date first, or you'll get a negative number.
Try this lesson free →Example
Days between two dates
SELECT order_id,
order_date,
ship_date,
ship_date - order_date AS days_to_ship
FROM orders| order_id | order_date | ship_date | days_to_ship |
|---|---|---|---|
| O2001 | 2024-03-01 | 2024-03-03 | 2 |
| O2002 | 2024-03-05 | 2024-03-10 | 5 |
| O2003 | 2024-03-07 | 2024-03-08 | 1 |
Step by step
- The later date minus the earlier one gives the days between.
SELECT order_id, order_date, ship_date, ship_date - order_date AS days_to_ship FROM orders - The other way round gives a negative number.
SELECT order_id, order_date, ship_date, ship_date - order_date AS days_to_ship FROM orders - Filter on it, like any number.
SELECT order_id, order_date, ship_date, ship_date - order_date AS days_to_ship FROM orders
Practice
1. Using orders, show order_id, order_date and ship_date, and next to them how many days each order took to ship. Name it days_to_ship.
SELECT order_id, order_date, ship_date, ship_date - order_date AS days_to_ship FROM orders2. Using promotions, show promo_name, start_date and end_date, and how many days each promotion ran from start to end. Name it days_running.
SELECT promo_name, start_date, end_date, end_date - start_date AS days_running FROM promotions3. Using returns, show return_id, order_date and return_date, and how many days after ordering each item came back. Name it days_to_return.
SELECT return_id, order_date, return_date, return_date - order_date AS days_to_return FROM returns4. Using orders, show the order_id of every order that took more than 3 days to ship.
SELECT order_id FROM orders WHERE ship_date - order_date > 35. Using orders, what is the average number of days to ship, rounded to 1 decimal place? Name it avg_days_to_ship.
SELECT ROUND(AVG(ship_date - order_date), 1) AS avg_days_to_ship FROM ordersLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →