SQL UNIX_TIMESTAMP function
Returns seconds since 1970-01-01 00:00:00 UTC, the interchange format for APIs, key ranges and compact time storage.
- Categoria
- Dates & times
- Returns
integer (fractional on PostgreSQL)- In this category
- 51 of 121
Sintaxe
UNIX_TIMESTAMP(d) -- MySQL
EXTRACT(epoch FROM ts) -- PostgreSQL
strftime('%s', ts) -- SQLite
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | DATEDIFF_BIG(second, '1970-01-01', d) |
| PostgreSQL | Different name or syntax | EXTRACT(epoch FROM ts) |
| MySQL | Sim | Supported under this name. |
| SQLite | Different name or syntax | unixepoch(ts) (3.38+) or strftime('%s', ts) |
| Oracle | Different name or syntax | (CAST(d AS DATE) - DATE '1970-01-01') * 86400 |
Exemplos
MySQL
SELECT UNIX_TIMESTAMP(created_at) AS epoch FROM orders;
PostgreSQL
SELECT EXTRACT(epoch FROM created_at)::bigint AS epoch FROM orders;
SQLite
SELECT unixepoch(created_at) AS epoch FROM orders;
SQL Server
SELECT DATEDIFF_BIG(SECOND, '1970-01-01', created_at) AS epoch FROM orders;
Bom saber
- The epoch is UTC: MySQL's UNIX_TIMESTAMP() applies the session time_zone to zone-less datetimes first, so a naive column shifts with the session.
- SQL Server's DATEDIFF returns int, so DATEDIFF(second, '1970-01-01', d) overflows for dates after 2038-01-19. DATEDIFF_BIG returns bigint and has no such limit.
- PostgreSQL's EXTRACT(epoch) keeps the fraction (numeric since version 14). Cast to bigint for whole seconds, or multiply by 1000 first for the millisecond epochs JavaScript uses.
Questions about UNIX_TIMESTAMP
Why is my epoch off by hours?
The input was interpreted in the wrong zone. MySQL applies the session time_zone to zone-less datetimes; store UTC or pass a timestamp with zone.
How do I get milliseconds?
Multiply by 1000. On MySQL, UNIX_TIMESTAMP returns whole seconds for a date argument; pass a datetime with fraction (NOW(3)) to keep sub-second digits.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Convert a Unix timestamp to a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Get the Unix timestamp of a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Convert between Unix epoch and timestamps in SQL Snippet
- Bucket timestamps into 5-minute windows in SQL Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.