Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 31/ 160
02. Aggregations, Functions & Data Manipulation

Date & Time Extraction (EXTRACT, DATE_PART, DATE_TRUNC)

Pull year/month/day parts and truncate timestamps to reporting grains.

IntermediateEXTRACT · DATE_PART3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Busiest hours of the dayQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  EXTRACT(3    HOUR4    FROM5      created_at6  ) AS HOUR,7  COUNT(*)8FROM9  orders10GROUP BY11  112ORDER BY13  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
hourcount
842
9118
10156
11139

Note: Illustrative hourly counts; EXTRACT uses the timestamp's or session's time-zone interpretation.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Daily orders in ISTQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  date_trunc(3    'day',4    created_at AT TIME ZONE 'Asia/Kolkata'5  ) AS day_ist,6  COUNT(*)7FROM8  orders9WHERE10  created_at >= '2026-11-01 00:00+05:30'11GROUP BY12  113ORDER BY14  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
day_istcount
2026-11-01 00:00:00284
2026-11-02 00:00:00317
2026-11-03 00:00:00301

Note: Illustrative IST calendar-day counts; timestamp output is timezone-free here because of AT TIME ZONE.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Convert the timezone before truncating, and filter with ranges.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Question

Decide: part or period?

"Which hour or weekday?" needs EXTRACT. "Which day, week or month?" needs DATE_TRUNC.

Focus at this step

hour of day → EXTRACT · month → DATE_TRUNC

What to watch at this step
Trends
DATE_TRUNC
Tip: use ← → to move between steps

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

EXTRACT / DATE_PART
Best for: Hour-of-day, weekday or month-of-year patterns

Strengths: Returns a simple number that's easy to group and compare.

Watch out: Loses the rest of the date (which year, which day).

DATE_TRUNC
Best for: Time-series buckets for trends and charts

Strengths: Keeps a real timestamp; sorts and charts correctly.

Watch out: Not available in MySQL; timezone-sensitive.

TO_CHAR / DATE_FORMAT
Best for: Display labels like 'Nov 2026'

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?
Interview tip: Explain the difference with one timestamp, then mention timezones. The timezone point is the one that shows you've reconciled real reports.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Numeric & Math Functions (ROUND, CEIL, FLOOR, ABS, MOD, POWER)
Next topic
Date Arithmetic, Intervals & Formatting (AGE, NOW(), CURRENT_DATE, TO_CHAR)