SQL ยท Chapter 25 of 42

Date Functions

Every database has functions to extract, format and compute dates. Common ones: `NOW()`, `CURRENT_DATE`, `DATE_ADD`, `DATE_DIFF`, `EXTRACT`, `DATE_TRUNC`.

Exact names vary โ€” check your database's docs.

Extract parts

`EXTRACT(YEAR FROM ts)`, `EXTRACT(MONTH FROM ts)` pull single fields.

Truncation

`DATE_TRUNC('month', ts)` rounds down to the first day of the month โ€” great for time-series bucketing.

Example 1 (sql)
SELECT NOW(), CURRENT_DATE;
Output
2026-07-29 12:34:00 | 2026-07-29

Current timestamp and date.

Example 2 (sql)
SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*)
FROM orders
GROUP BY 1
ORDER BY 1;
Output
orders per month

Bucket by month (Postgres syntax).

Key points

  • NOW() = current timestamp.
  • EXTRACT pulls a field.
  • DATE_TRUNC buckets by unit.
  • Store timestamps in UTC.
๐Ÿ’ก Note: PostgreSQL `DATE_TRUNC`, MySQL `DATE_FORMAT`, SQL Server `DATEPART`/`FORMAT`. Different names, same job.

๐Ÿ“ Quick Quiz

1. Which returns the current date?

2. EXTRACT(YEAR FROM ts) returns:

3. Best practice for timestamp storage: