Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 03 / Topic 7 of 9

Dates and times

Postgres is unusually good at time. The clock functions first:

  • now() — the current moment (timestamptz), frozen for the whole transaction
  • current_date — today's date

Both change per run, so this lesson works with shopdb's fixed dates instead. date_trunc floors a moment to a boundary — the key to "group by month" reports:

SELECT first_name, signup_date,
       date_trunc('month', signup_date)::date AS signup_month
FROM customers
ORDER BY signup_date
LIMIT 3;
 first_name | signup_date | signup_month 
------------+-------------+--------------
 Asha       | 2025-01-05  | 2025-01-01
 Ravi       | 2025-01-20  | 2025-01-01
 Meera      | 2025-02-11  | 2025-02-01
(3 rows)

extract pulls one field out; date subtraction gives whole days; age gives a human-ish interval:

SELECT order_id, order_date,
       extract(month FROM order_date)       AS month,
       DATE '2025-06-01' - order_date       AS days_before_june,
       age(DATE '2025-06-01', order_date)   AS age_at_june
FROM orders
ORDER BY order_id
LIMIT 3;
 order_id | order_date | month | days_before_june |  age_at_june   
----------+------------+-------+------------------+----------------
        1 | 2025-01-10 |     1 |              142 | 4 mons 22 days
        2 | 2025-01-25 |     1 |              127 | 4 mons 7 days
        3 | 2025-02-14 |     2 |              107 | 3 mons 15 days
(3 rows)

Interval arithmetic reads like English — and has one famous subtlety: month arithmetic clamps to real calendar days:

SELECT DATE '2025-01-31' + INTERVAL '1 month' AS clamped,
       DATE '2025-03-15' + INTERVAL '2 days'  AS two_days_on,
       TIMESTAMPTZ '2025-01-10 10:15+05:30' + INTERVAL '90 minutes' AS later;
       clamped       |     two_days_on     |           later           
---------------------+---------------------+---------------------------
 2025-02-28 00:00:00 | 2025-03-17 00:00:00 | 2025-01-10 11:45:00+05:30
(1 row)

January 31 plus a month is February 28 — not an error, not March 3. (Also note: date + interval returns a timestamp.) Writing dates, stick to ISO '2025-01-26' — unambiguous, sortable, what Postgres speaks natively.

🧪 Quick quiz — answer from memory, then check.

  1. What does DATE '2025-01-31' + INTERVAL '1 month' return?
  2. Which function turns any date into "the first moment of its month"?
Show the answers
  1. 2025-02-28 00:00:00 — clamped to the month's real last day, as a timestamp.
  2. date_trunc('month', d) — cast with ::date if you want a plain date back.

Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.

Search the guide