SQL · Module 5 · Lesson 31 min read

Date & Time Functions

Current values

now(), CURRENT_DATE, CURRENT_TIME, localtimestamp

EXTRACT – get one part of a date

EXTRACT(field FROM date) → a number

  • year, quarter, month, day, hour, minute
  • dow (day of week, 0 = Sunday), isodow (1 = Monday … 7 = Sunday), doy (day of year), week
  • epoch – seconds since 1970-01-01

date_part('month', date) does the same thing.

DATE_TRUNC – round down to a unit ⭐

date_trunc('month', spent_on) → the first moment of that month Perfect for grouping by month/week/year in reports: GROUP BY date_trunc('month', spent_on)

TO_CHAR – format for display

PatternOutput
'YYYY-MM-DD'2026-11-24
'DD Mon YYYY'24 Nov 2026
'FMDay, DD FMMonth'Tuesday, 24 November
'Mon YYYY'Nov 2026
'HH24:MI'14:30
FM removes padding spaces.

Parsing text into dates

  • '2026-11-24'::date
  • to_date('24/11/2026', 'DD/MM/YYYY'), to_timestamp(text, format)
  • make_date(2026, 11, 24)

Intervals & differences

  • date + 7, date - 30
  • now() - INTERVAL '30 days', INTERVAL '1 month'
  • age(later, earlier) → 1 year 2 mons 3 days (human-friendly)
  • date2 - date1 → days as an integer

Useful patterns

  • This month: spent_on >= date_trunc('month', CURRENT_DATE)
  • Last 30 days: spent_on >= CURRENT_DATE - 30
  • Last day of the month: (date_trunc('month', d) + INTERVAL '1 month - 1 day')::date
  • Weekends: EXTRACT(isodow FROM d) IN (6, 7)
  • generate_series – a row for every day/month (Unit 13)

Example

SQL
SELECT spent_on,
       EXTRACT(year FROM spent_on)          AS yr,
       EXTRACT(month FROM spent_on)         AS mon,
       EXTRACT(isodow FROM spent_on)        AS weekday_no,      -- 1 = Monday
       to_char(spent_on, 'FMDay, DD Mon')   AS pretty,
       date_trunc('month', spent_on)::date  AS month_start
FROM expenses
WHERE id = 1;
-- 2026-09-03 | 2026 | 9 | 4 | Thursday, 03 Sep | 2026-09-01

-- Monthly spending report ⭐
SELECT to_char(date_trunc('month', spent_on), 'Mon YYYY') AS month,
       count(*)                                         AS expenses,
       sum(amount)                                      AS total
FROM expenses
GROUP BY date_trunc('month', spent_on)
ORDER BY date_trunc('month', spent_on);
-- Sep 2026 | 11 | 18230.00
-- Oct 2026 | 10 | 26090.00
-- Nov 2026 | 10 | 32290.00

-- Weekend vs weekday spending
SELECT CASE WHEN EXTRACT(isodow FROM spent_on) IN (6, 7) THEN 'Weekend' ELSE 'Weekday' END AS day_type,
       sum(amount) AS total
FROM expenses
GROUP BY 1;

-- How long has each user been a member? (as of 24 Nov 2026)
SELECT name, age(DATE '2026-11-24', created_at::date) AS membership
FROM users ORDER BY created_at LIMIT 2;
-- Asha Sharma | 10 mons 14 days

-- Parsing and building dates
SELECT to_date('24/11/2026', 'DD/MM/YYYY')                     AS parsed,
       make_date(2026, 2, 1) + INTERVAL '1 month - 1 day'       AS end_of_feb,
       DATE '2026-11-24' - 30                                   AS thirty_days_ago;