BBampaa

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

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

Result:

order_monthtotal_revenue
2024-03-01 00:00:00203.49
2024-04-01 00:00:00265.25
2024-05-01 00:00:00340.75

Step by step

  1. 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
  2. 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
  3. 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

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

1. Using orders, write a query that rounds order_date down to the start of the year.
SELECT DATE_TRUNC('year', order_date) FROM orders
2. 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_sales
3. Using promotions, write a query that rounds start_date down to the start of the month.
SELECT DATE_TRUNC('month', start_date) FROM promotions
4. Using reviews, write a query that rounds review_date down to the start of the week.
SELECT DATE_TRUNC('week', review_date) FROM reviews
5. 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 employees

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