MySQL EXTRACT() Function
MySQL EXTRACT(): Pull Specific Date and Time Units
The EXTRACT() function extracts a single calendar or clock component—such as YEAR, QUARTER, MONTH, HOUR, or even compound units like YEAR_MONTH—from a date or time expression. It follows ANSI SQL syntax and always returns an integer.
Data engineers favor EXTRACT() when writing portable queries across MySQL and PostgreSQL without relying on vendor-specific functions.
Syntax
Unlike most MySQL functions, EXTRACT() uses the FROM keyword instead of a comma:
EXTRACT(unit FROM date_or_time_expr)
unit: Any valid interval unit such asYEAR,QUARTER,MONTH,WEEK,DAY,HOUR,MINUTE,SECOND,MICROSECOND, or compound units likeYEAR_MONTHandDAY_HOUR.date_or_time_expr: ADATE,DATETIME,TIME, or valid date/time string.
Practical Example
Suppose you build a quarterly and monthly revenue breakdown from demo_orders using EXTRACT().
SELECT
order_id,
created_at,
EXTRACT(YEAR FROM created_at) AS order_year,
EXTRACT(QUARTER FROM created_at) AS order_quarter,
EXTRACT(YEAR_MONTH FROM created_at) AS yyyymm_key
FROM demo_orders
WHERE order_id IN (101, 105);
| order_id | created_at | order_year | order_quarter | yyyymm_key |
|---|---|---|---|---|
| 101 | 2026-02-18 11:20:00 | 2026 | 1 | 202602 |
| 105 | 2026-05-12 16:45:00 | 2026 | 2 | 202605 |
Notice EXTRACT(YEAR_MONTH FROM created_at) outputs an integer 202605, which is fast to sort and join against integer date-dimension keys.
Common Mistakes & NULL Behavior
Avoid these common mistakes when calling EXTRACT():
- Comma syntax error: Writing
EXTRACT(YEAR, created_at)fails immediately. You must writeEXTRACT(YEAR FROM created_at). NULLor malformed dates returnNULL: PassingNULLor'2026-02-30'yieldsNULL.- Extracting time units from a
DATE: RunningEXTRACT(HOUR FROM '2026-05-12')returns0because a bareDATEhas no time component. - Compound unit output is an integer, not a formatted string:
EXTRACT(YEAR_MONTH FROM '2026-05-12')returns202605, without a hyphen. UseDATE_FORMAT(d, '%Y-%m')if you need'2026-05'.
Frequently Asked Questions
What is the difference between EXTRACT(MONTH FROM d) and MONTH(d)?
For single units like YEAR, MONTH, DAY, and HOUR, EXTRACT() returns the same integer as YEAR(d), MONTH(d), DAY(d), and HOUR(d), but EXTRACT() uses standard ANSI SQL syntax.
Can EXTRACT() pull hours from a TIME duration over 24 hours?
Yes. For example, EXTRACT(HOUR FROM '36:15:00') returns 36, matching HOUR().
Why does EXTRACT(WEEK FROM d) sometimes differ from ISO week numbers?
EXTRACT(WEEK FROM d) uses the server's default_week_format variable (which defaults to 0, Sunday start). Use WEEKOFYEAR(d) for consistent ISO-8601 week numbers.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.