BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Days between two dates

SELECT order_id,
       order_date,
       ship_date,
       ship_date - order_date AS days_to_ship
FROM orders

Result:

order_idorder_dateship_datedays_to_ship
O20012024-03-012024-03-032
O20022024-03-052024-03-105
O20032024-03-072024-03-081

Step by step

  1. 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
  2. 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
  3. Filter on it, like any number.
    SELECT order_id, order_date, ship_date, ship_date - order_date AS days_to_ship FROM orders

Practice

Try each one in your head first, then open the answer.

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 orders
2. 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 promotions
3. 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 returns
4. 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 > 3
5. 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 orders

Learn 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 →
About 5–10 minutes · no sign-up needed