BBampaa

Lessons › SQL › Chapter 4: Shaping data

SQL lesson

Date difference functions

Date difference functions calculate the number of days (or hours, months, or other units) between two dates.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

How many 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. AS gives a column a friendlier name in the result.
    SELECT order_id, ship_date - order_date AS days_to_ship
  2. FROM tells SQL which table to pull the data from.
    SELECT order_id, 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, write a query to find the number of days between today and order_date.
SELECT CURRENT_DATE - order_date FROM orders
2. Using shipments, write a query to find the number of days between today and ship_date.
SELECT CURRENT_DATE - ship_date FROM shipments
3. Using promotions, write a query to find the number of days between end_date and start_date.
SELECT end_date - start_date FROM promotions
4. Using store_sales, write a query to find the number of days between today and sale_date.
SELECT CURRENT_DATE - sale_date FROM store_sales
5. Using returns, write a query to find the number of days between today and return_date.
SELECT CURRENT_DATE - return_date FROM returns

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