AI Hints
Home›PostgreSQL Tutorial›Dates and Times
PostgreSQL · Lesson 15 of 120

Intervals and date_trunc

Date maths.

⏱ 2 min read▶ Video at 12:22🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

How many days since a customer joined? What date is thirty days after an order? And how many orders per month? Intervals and date trunc answer all three.

  • Days since?
  • 30 days later?
  • Per month?

Date maths

Adding an interval moves a date. Subtracting two dates gives the number of days. Run it. Return deadlines, and the days between joining and ordering.

query.sqlsql
SELECT o.order_id,
       (o.order_date + interval '30 days')::date AS return_by,
       o.order_date - c.joined AS days_after_joining
FROM orders o JOIN customers c USING (customer_id)
ORDER BY o.order_id
LIMIT 3;
Output
 order_id | return_by  | days_after_joining
----------+------------+--------------------
     1001 | 2025-04-05 |                247
     1002 | 2024-12-24 |                145
     1003 | 2024-07-22 |                500
(3 rows)

Orders per month

Date trunc rounds each date down to the start of its month. Then we group and count. Run it. Orders in the first four months of twenty twenty five.

query.sqlsql
SELECT date_trunc('month', order_date)::date AS month,
       count(*) AS orders
FROM orders
WHERE order_date BETWEEN '2025-01-01' AND '2025-04-30'
GROUP BY month
ORDER BY month;
Output
   month    | orders
------------+--------
 2025-01-01 |     69
 2025-02-01 |     75
 2025-03-01 |     61
 2025-04-01 |     73
(4 rows)

Summary

Intervals move dates, subtracting dates gives days, and date trunc groups by month. Next, creating your own tables.

Key takeaways
  • interval
  • date - date
  • date_trunc
Next up: CREATE TABLE — your own tables