Lessons › SQL › Chapter 4: Shaping data
SQL lesson
DATE_TRUNC() for rounding dates to year, month, week or day
DATE_TRUNC rounds a date down to the start of a month, week or year. 2024-03-19 becomes 2024-03-01. Then every March order has the same date, so you can GROUP BY it and total each month.
Try this lesson free →Example
Round dates down
SELECT DATE_TRUNC('month', order_date) AS order_month,
SUM(revenue) AS total_revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY order_month| order_month | total_revenue |
|---|---|
| 2024-03-01 00:00:00 | 203.49 |
| 2024-04-01 00:00:00 | 265.25 |
| 2024-05-01 00:00:00 | 340.75 |
Step by step
- Every date becomes the 1st of its month.
SELECT DATE_TRUNC('month', order_date) AS order_month, SUM(revenue) AS total_revenue FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY order_month - Pick how far to round down.
SELECT DATE_TRUNC('month', order_date) AS order_month, SUM(revenue) AS total_revenue FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY order_month - Same-month orders now match, so you can total each month.
SELECT DATE_TRUNC('month', order_date) AS order_month, SUM(revenue) AS total_revenue FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY order_month
Practice
1. Using orders, write a query that rounds order_date down to the start of the year.
SELECT DATE_TRUNC('year', order_date) FROM orders2. Using store_sales, write a query that rounds sale_date down to the start of the month.
SELECT DATE_TRUNC('month', sale_date) FROM store_sales3. Using promotions, write a query that rounds start_date down to the start of the month.
SELECT DATE_TRUNC('month', start_date) FROM promotions4. Using reviews, write a query that rounds review_date down to the start of the week.
SELECT DATE_TRUNC('week', review_date) FROM reviews5. Using employees, show each full_name with their hire_date rounded down to the start of the month.
SELECT full_name, DATE_TRUNC('month', hire_date) FROM employeesLearn 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 →