MySQL TO_DAYS() Function
MySQL TO_DAYS() Function
The MySQL TO_DAYS() function converts a DATE or DATETIME expression into the integer number of days since year 0 (0000-00-00). For instance, TO_DAYS('0000-01-01') returns 1.
Database administrators commonly use TO_DAYS() in RANGE table partitioning expressions for large time-series tables, because TO_DAYS(created_at) produces a monotonically increasing integer that MySQL's partition pruner optimizes natively.
It is the mathematical inverse of FROM_DAYS(), though TO_DAYS() discards any time-of-day portion before computing the integer day count.
Syntax
TO_DAYS(date)
date: A validDATE,DATETIME, orTIMESTAMPexpression.
Practical Example
Using demo_customers, you can inspect the integer day numbers for signup dates and compute the exact number of days between two dates by subtracting TO_DAYS() values.
SELECT
customer_id,
signup_date,
TO_DAYS(signup_date) AS days_since_year_zero,
TO_DAYS('2026-05-10') - TO_DAYS(signup_date) AS days_since_signup
FROM demo_customers
WHERE customer_id IN (1, 2, 3);
| customer_id | signup_date | days_since_year_zero | days_since_signup |
|---|---|---|---|
| 1 | 2025-11-01 | 739921 | 190 |
| 2 | 2026-05-01 | 740102 | 9 |
| 3 | 2026-05-10 | 740111 | 0 |
Notice that TO_DAYS('2026-05-10') - TO_DAYS(signup_date) gives the exact day count matching DATEDIFF('2026-05-10', signup_date).
Common Mistakes & NULL Behavior
Do not use TO_DAYS() for historical dates before the Gregorian calendar adoption in 1582 ('1582-10-15'). MySQL explicitly notes that TO_DAYS() does not account for the 10-day calendar gap lost when switching from the Julian to the Gregorian calendar.
Also avoid passing TO_DAYS() in standard WHERE TO_DAYS(created_at) > ... queries on unpartitioned tables; wrapping the column prevents normal B-tree index usage. Use direct date comparisons like created_at > '2026-05-01' instead.
TO_DAYS() returns NULL when date is NULL, invalid (such as '2026-02-30'), or '0000-00-00'. Zero-month dates like '2026-00-10' also return NULL.
Frequently Asked Questions
What is the difference between TO_DAYS() and DATEDIFF()?
TO_DAYS(d) converts a single date into days since year 0, while DATEDIFF(d1, d2) directly computes d1 - d2 in days between two dates.
Does TO_DAYS() include the time portion of a DATETIME?
No. TO_DAYS('2026-05-10 23:59:59') and TO_DAYS('2026-05-10 00:00:01') return the exact same integer (740111).
Why is TO_DAYS() popular in table partitioning?
MySQL supports partition pruning for PARTITION BY RANGE (TO_DAYS(col)), letting queries on col skip irrelevant partitions automatically.
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.