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 →Example
How many 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
- AS gives a column a friendlier name in the result.
SELECT order_id, ship_date - order_date AS days_to_ship - FROM tells SQL which table to pull the data from.
SELECT order_id, ship_date - order_date AS days_to_ship FROM orders;
Practice
1. Using orders, write a query to find the number of days between today and order_date.
SELECT CURRENT_DATE - order_date FROM orders2. Using shipments, write a query to find the number of days between today and ship_date.
SELECT CURRENT_DATE - ship_date FROM shipments3. Using promotions, write a query to find the number of days between end_date and start_date.
SELECT end_date - start_date FROM promotions4. Using store_sales, write a query to find the number of days between today and sale_date.
SELECT CURRENT_DATE - sale_date FROM store_sales5. Using returns, write a query to find the number of days between today and return_date.
SELECT CURRENT_DATE - return_date FROM returnsLearn 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 →