// dates & times reference

SQL TO_SECONDS function

Returns the number of seconds from year 0 to a date or datetime: TO_DAYS scaled by 86,400, plus the time when given a datetime.

Catégorie
Dates & times
Returns
integer
In this category
55 of 121

Syntaxe

TO_SECONDS('2024-01-15')
TO_SECONDS('2024-01-15 09:30:00')

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

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax DATEDIFF_BIG(second, '0001-01-01', d) + 31622400; plain DATEDIFF overflows int
PostgreSQL Different name or syntax EXTRACT(epoch FROM ts) + 62167219200
MySQL Oui Supported under this name.
SQLite Different name or syntax unixepoch(ts) + 62167219200
Oracle Different name or syntax (d - DATE '1970-01-01') * 86400 + 62167219200

Exemples

MySQL

SELECT TO_SECONDS('2024-01-15 09:30:00') AS s;

MySQL

SELECT UNIX_TIMESTAMP('2024-01-15') AS epoch, TO_SECONDS('2024-01-15') AS since_year0;

Bon à savoir

  • It is not epoch time: TO_SECONDS('1970-01-01') is 62,167,219,200, so add or subtract that constant to move between the two scales.
  • With a date-only argument the time counts as midnight; with a datetime the seconds include the clock. Mixed inputs shift results by the time of day.
  • Only MySQL has it. It takes the value as written with no time-zone conversion, whereas UNIX_TIMESTAMP first converts from the session time_zone to UTC.

Questions about TO_SECONDS

Is TO_SECONDS the same as UNIX_TIMESTAMP?

No: TO_SECONDS counts from year 0, UNIX_TIMESTAMP from 1970 UTC. For a UTC session the difference is exactly 62,167,219,200 seconds.

Where is TO_SECONDS actually used?

Mostly partition pruning: MySQL's partitioning can prune on TO_SECONDS(expr) ranges the way it does on TO_DAYS.

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.