Date & Time Extraction (EXTRACT, DATE_PART, DATE_TRUNC)
Pull year/month/day parts and truncate timestamps to reporting grains.
In plain words
EXTRACT takes out a piece, like just the month number. DATE_TRUNC rounds a time down to the start of its day, week or month.
Think of it like…
EXTRACT reads one hand of a clock ("it's 11 o'clock"). DATE_TRUNC is a calendar page: it tells you which specific month you're in, including the year.
Where you’ve seen it
Monthly revenue: SELECT date_trunc('month', created_at) AS month, SUM(amount) FROM orders GROUP BY 1 ORDER BY 1; gives one row per calendar month. Grouping by EXTRACT(MONTH FROM created_at) instead would add November 2025 and November 2026 together.
Words you’ll hear
- EXTRACT / DATE_PART
- Return one numeric component: year, month, day, dow, hour, epoch.
- DATE_TRUNC
- Rounds a timestamp down to the start of a period; keeps the full date.
- DOW vs ISODOW
- PostgreSQL day-of-week: 0 = Sunday (dow) or 1 = Monday … 7 = Sunday (isodow).
- Timezone
- timestamptz values are truncated in the session's timezone unless you convert first.
Visual diagram
Theory & example queries
EXTRACT for parts, DATE_TRUNC for periods
Use EXTRACT when you care about the component on its own: orders by hour of day (EXTRACT(HOUR FROM ts)), weekday patterns (EXTRACT(ISODOW FROM ts)), or the age of something in seconds (EXTRACT(EPOCH FROM now() - created_at)).
Use DATE_TRUNC to build time buckets for trends: 'day', 'week' (which starts on Monday), 'month', 'quarter', 'year'. Its result is still a timestamp, so it sorts correctly and works directly as a chart axis. If you group by EXTRACT(MONTH) alone, every year's November lands in the same group.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT EXTRACT( HOUR FROM created_at ) AS HOUR, COUNT(*)FROM ordersGROUP BY 1ORDER BY 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output4 sample rows
| hour | count |
|---|---|
| 8 | 42 |
| 9 | 118 |
| 10 | 156 |
| 11 | 139 |
Note: Illustrative hourly counts; EXTRACT uses the timestamp's or session's time-zone interpretation.
Key takeaway: EXTRACT for "which hour/weekday"; DATE_TRUNC for "which day/month".
Timezones, dialects and indexes
A timestamptz is stored as an absolute instant; DATE_TRUNC('day', ts) uses the session's timezone to decide where a day starts. For reports in Indian time, convert explicitly: date_trunc('day', created_at AT TIME ZONE 'Asia/Kolkata'). Otherwise an order at 01:00 IST can be counted on the previous UTC day.
Dialects differ: MySQL has YEAR(), MONTH() and DATE_FORMAT but no DATE_TRUNC; SQL Server has DATEPART and, since 2022, DATETRUNC; BigQuery and Snowflake have DATE_TRUNC with their own argument order. In WHERE clauses, avoid wrapping the column (WHERE EXTRACT(YEAR FROM created_at) = 2026); write a range so the index on created_at still works.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT date_trunc( 'day', created_at AT TIME ZONE 'Asia/Kolkata' ) AS day_ist, COUNT(*)FROM ordersWHERE created_at >= '2026-11-01 00:00+05:30'GROUP BY 1ORDER BY 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| day_ist | count |
|---|---|
| 2026-11-01 00:00:00 | 284 |
| 2026-11-02 00:00:00 | 317 |
| 2026-11-03 00:00:00 | 301 |
Note: Illustrative IST calendar-day counts; timestamp output is timezone-free here because of AT TIME ZONE.
Key takeaway: Convert the timezone before truncating, and filter with ranges.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide: part or period?
"Which hour or weekday?" needs EXTRACT. "Which day, week or month?" needs DATE_TRUNC.
hour of day → EXTRACT · month → DATE_TRUNC
When to use it & trade-offs
What it is
EXTRACT(field FROM ts) pulls one part out of a date or timestamp: the year, month, day of week, hour. PostgreSQL's DATE_PART('month', ts) does the same. DATE_TRUNC('month', ts) keeps the timestamp but rounds it down to the start of the period, such as 2026-11-01 00:00, which makes it the standard way to group events by day, week, month or year.
Why it matters: Almost every report is grouped by time, and the two functions answer different questions. EXTRACT(MONTH) gives 11 for November of every year, while DATE_TRUNC('month') gives November 2026 specifically. Mixing them up, and ignoring timezones, are the classic date bugs in analytics.
When to reach for it
- Daily, weekly and monthly trend reports
- Hour-of-day and weekday activity patterns
- Age and duration calculations with EPOCH
When to avoid or be careful
- Grouping by EXTRACT(MONTH) for multi-year trends
- Truncating timestamptz without thinking about the timezone
- Sorting by formatted text labels
EXTRACT vs DATE_TRUNC vs formatting functions
Strengths: Returns a simple number that's easy to group and compare.
Watch out: Loses the rest of the date (which year, which day).
Strengths: Keeps a real timestamp; sorts and charts correctly.
Watch out: Not available in MySQL; timezone-sensitive.
Strengths: Human-readable output.
Watch out: Returns text, which sorts alphabetically, not by date.
Interview signals & numbers to know
When this topic comes up
- “Revenue per month”
- “Which hour has the most orders?”
- “Numbers don't match the finance team's daily totals”
- Weekly cohorts
- Timezone bugs
Benchmarks & rules of thumb
- 0
- Sunday in PostgreSQL's DOW
- Monday
- start of a DATE_TRUNC('week') bucket
- SQL Server 2022
- added DATETRUNC
Common mistakes & follow-ups
Common interview mistakes
- Grouping by EXTRACT(MONTH FROM ts) and merging the same month from different years.
- Truncating UTC timestamps to days for an Indian business, so late-night orders land on the wrong day.
- Sorting by TO_CHAR(ts, 'Mon YYYY'), which puts Apr before Jan.
Likely interviewer follow-ups
- What's the difference between EXTRACT and DATE_TRUNC?
- How would you group orders by week in India's timezone?
- How would you do monthly grouping in MySQL, which has no DATE_TRUNC?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Date & Time Extraction (EXTRACT, DATE_PART, DATE_TRUNC) with hands-on SQL practice and interview Q&A.