Full answer
Test data:
sql
CREATE TABLE members (name text, born date, joined timestamp);
INSERT INTO members VALUES
('Asha', '1998-02-14', '2025-01-31 09:15'),
('Ben', '2004-11-30', '2026-03-05 18:40');sql
SELECT name, extract(year FROM born) AS birth_year, extract(dow FROM born) AS weekday, date_trunc('month', joined) AS join_month FROM members ORDER BY name;Result:
text
name | birth_year | weekday | join_month
------+------------+---------+---------------------
Asha | 1998 | 6 | 2025-01-01 00:00:00
Ben | 2004 | 2 | 2026-03-01 00:00:00
(2 rows)sql
SELECT name, age(date '2026-12-04', born) AS age, date '2026-12-04' - born AS days_alive FROM members ORDER BY name;Output:
text
name | age | days_alive
------+-------------------------+------------
Asha | 28 years 9 mons 18 days | 10520
Ben | 22 years 4 days | 8039
(2 rows)sql
SELECT date '2025-01-31' + interval '1 month' AS plus_month, timestamp '2026-03-05 18:40' - timestamp '2026-03-01 08:00' AS gap;PostgreSQL returns:
text
plus_month | gap
---------------------+-----------------
2025-02-28 00:00:00 | 4 days 10:40:00
(1 row)extract returns numeric values; dow counts Sunday as 0, so Asha's birthday fell on a Saturday (6). date_trunc returns a timestamp at the start of the month. age() gives a readable interval such as '28 years 9 mons 18 days', while plain date subtraction returns days. Adding one month to 31 January gives 28 February 2025, because PostgreSQL clamps to the last day of the shorter month. Timestamp subtraction yields an interval of days and hours.
sql
CREATE TABLE members (name text, born date, joined timestamp);
INSERT INTO members VALUES
('Asha', '1998-02-14', '2025-01-31 09:15'),
('Ben', '2004-11-30', '2026-03-05 18:40');
SELECT name, extract(year FROM born) AS birth_year, extract(dow FROM born) AS weekday, date_trunc('month', joined) AS join_month FROM members ORDER BY name;
SELECT name, age(date '2026-12-04', born) AS age, date '2026-12-04' - born AS days_alive FROM members ORDER BY name;
SELECT date '2025-01-31' + interval '1 month' AS plus_month, timestamp '2026-03-05 18:40' - timestamp '2026-03-01 08:00' AS gap;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- extract for parts, date_trunc for rounding
- date minus date gives days
- age() gives years, months and days
- Month arithmetic clamps to month end
- Timestamp subtraction gives an interval
Common mistakes
- Calculating age by dividing days by 365
- Expecting 31 January plus a month to be 3 March
Follow-ups
- How do you group sales by ISO week?
- What does date_bin do?
Tips
- Show month-end clamping