Skip to main content
Albero Academy

Date & Time Functions

Work with dates — the current time, extracting parts, date arithmetic, truncation for grouping, and formatting.

Chapter 11SQL14 min readBeginner friendly
  • #SQL
  • #Dates
  • #Functions

Dates power a huge share of analysis — trends over time, cohorts, "last 30 days". SQL has rich date handling, though function names vary by database (Postgres syntax shown here). The concepts — extract, add/subtract, truncate — carry across all of them.

Current date & time

now
SELECT CURRENT_DATE; -- 2026-01-12
SELECT CURRENT_TIMESTAMP; -- with time
SELECT NOW(); -- Postgres/MySQL

Extracting parts

pull pieces out
SELECT EXTRACT(YEAR FROM enrolled) AS year,
EXTRACT(MONTH FROM enrolled) AS month,
EXTRACT(DOW FROM enrolled) AS day_of_week
FROM students;
-- Group counts by month:
SELECT EXTRACT(MONTH FROM enrolled) AS m, COUNT(*)
FROM students GROUP BY m ORDER BY m;

Date arithmetic

add, subtract, diff
SELECT enrolled + INTERVAL '30 days' AS deadline;
SELECT CURRENT_DATE - enrolled AS days_enrolled; -- difference in days
SELECT AGE(CURRENT_DATE, enrolled); -- human-readable interval
-- Everyone who enrolled in the last 30 days:
WHERE enrolled >= CURRENT_DATE - INTERVAL '30 days';

Truncating for groups

DATE_TRUNC rounds a timestamp down to a unit — the key to grouping events by day, week or month for time-series reports:

time-series grouping
-- Sign-ups per month
SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*)
FROM signups
GROUP BY month
ORDER BY month;
SELECT TO_CHAR(enrolled, 'DD Mon YYYY'); -- format for display: '12 Jan 2026'

Practice

Count students enrolled per month with EXTRACT or DATE_TRUNC. Find everyone who enrolled in the last 30 days. Compute each student's days-since-enrolment, and format a date as "12 Jan 2026" for a report.

Key takeaways

  1. 01CURRENT_DATE / NOW() give the current date/time.
  2. 02EXTRACT(part FROM date) pulls out year/month/day/day-of-week.
  3. 03Add/subtract with INTERVAL; subtract two dates for a difference.
  4. 04DATE_TRUNC(unit, ts) buckets timestamps by day/week/month for time-series grouping.
  5. 05Store timestamps in UTC; convert to local time only for display.