// dates & times reference

SQL TO_DAYS function

Returns the calendar day number of a date, or a date back from that number: the classic MySQL idiom for day-count arithmetic.

Categoria
Dates & times
Returns
integer
In this category
54 of 121

Sintaxe

TO_DAYS('2024-01-15')  -- 739265
FROM_DAYS(739265)
DATEDIFF(day, 0, d)  -- SQL Server, days since 1900

Each block is a separate form. The support table and the examples show which engine takes which.

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax DATEDIFF(day, 0, d) counts from 1900-01-01; DATEADD(day, n, 0) reverses
PostgreSQL Different name or syntax d - DATE '0001-01-01' + 366 matches TO_DAYS
MySQL Sim Supported under this name.
SQLite Different name or syntax julianday(d), a different origin
Oracle Different name or syntax TO_CHAR(d, 'J'), a different origin

Exemplos

MySQL

SELECT TO_DAYS('2024-01-15') AS day_no;

MySQL

SELECT FROM_DAYS(TO_DAYS('2024-01-15') + 30) AS in_30_days;

SQL Server

SELECT DATEDIFF(DAY, 0, created_at) AS day_no FROM orders;

Bom saber

  • TO_DAYS counts from year 0 of MySQL's calendar, not 1970: TO_DAYS('2024-01-15') is 739265. Every engine's day number uses its own origin, so never compare them across engines.
  • It ignores the time part: 2024-01-15 00:01 and 23:59 give the same number. Good for daily keys; wrong for measuring spans shorter than a day.
  • FROM_DAYS is not meant for dates before 1582: MySQL counts days on the proleptic Gregorian calendar and ignores the switch from the Julian calendar.

Questions about TO_DAYS / FROM_DAYS

What is TO_DAYS used for?

Daily bucketing keys and date arithmetic in one integer: FROM_DAYS(TO_DAYS(d) + 30) is thirty days later, and equal TO_DAYS means the same calendar day.

Is the day number an epoch?

No. It counts from year 0 in MySQL's proleptic Gregorian calendar, not from 1970. SQLite's julianday uses a different origin again.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.