SQL EXTRACT
Pulls a single named part — year, month, day, and more — out of a date or timestamp, returning it as a plain number.
What & Why
EXTRACT(field FROM source) pulls one specific component out of a date or timestamp value and returns it as a number. The next several lessons cover each individual field (year, quarter, month, week, day, day of week, hour) one at a time — this lesson is about the general syntax they all share.
See How It Works
BUSINESS QUESTION
Marketing wants the signup year, month, and day shown beside every lead's original created_at value.
| id | campaign_id | created_at | qualified_at | converted_at | lead_score | source | country | |
|---|---|---|---|---|---|---|---|---|
| 301 | 1 | ana@example.com | 2024-01-21 09:10:00+00 | 2024-01-22 11:00:00+00 | 2024-02-02 10:00:00+00 | 86 | google_ads | US |
| 302 | 1 | ben@example.com | 2024-01-24 12:40:00+00 | NULL | NULL | 52 | google_ads | CA |
| 303 | 2 | chloe@example.com | 2024-02-16 08:30:00+00 | 2024-02-18 14:20:00+00 | NULL | 74 | GB | |
| 304 | 3 | dev@example.com | 2024-03-20 17:15:00+00 | 2024-03-21 09:00:00+00 | 2024-04-04 16:00:00+00 | 91 | US |
Watch the same timestamps expose three calendar fieldsStep 1 of 3
EXTRACT(YEAR FROM created_at)
| id | created_at | signup_year |
|---|---|---|
| 301 | 2024-01-21 09:10:00+00 | 2024 |
| 302 | 2024-01-24 12:40:00+00 | 2024 |
| 303 | 2024-02-16 08:30:00+00 | 2024 |
| 304 | 2024-03-20 17:15:00+00 | 2024 |
YEAR returns 2024 for each displayed lead while the original timestamp remains visible.
EXAMPLE QUERY
SELECT
id,
created_at,
EXTRACT(YEAR FROM created_at)::int AS signup_year,
EXTRACT(MONTH FROM created_at)::int AS signup_month,
EXTRACT(DAY FROM created_at)::int AS signup_day
FROM marketing.leads
ORDER BY created_at, id;Sign up free to try it on a real business scenario