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
SELECT CURRENT_DATE; -- 2026-01-12SELECT CURRENT_TIMESTAMP; -- with timeSELECT NOW(); -- Postgres/MySQL
Extracting parts
SELECT EXTRACT(YEAR FROM enrolled) AS year,EXTRACT(MONTH FROM enrolled) AS month,EXTRACT(DOW FROM enrolled) AS day_of_weekFROM students;-- Group counts by month:SELECT EXTRACT(MONTH FROM enrolled) AS m, COUNT(*)FROM students GROUP BY m ORDER BY m;
Date arithmetic
SELECT enrolled + INTERVAL '30 days' AS deadline;SELECT CURRENT_DATE - enrolled AS days_enrolled; -- difference in daysSELECT 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:
-- Sign-ups per monthSELECT DATE_TRUNC('month', created_at) AS month, COUNT(*)FROM signupsGROUP BY monthORDER 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
- 01CURRENT_DATE / NOW() give the current date/time.
- 02EXTRACT(part FROM date) pulls out year/month/day/day-of-week.
- 03Add/subtract with INTERVAL; subtract two dates for a difference.
- 04DATE_TRUNC(unit, ts) buckets timestamps by day/week/month for time-series grouping.
- 05Store timestamps in UTC; convert to local time only for display.
