// dialect comparison

Get the Unix timestamp of a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

Three engines have a function for it; in SQL Server and Oracle you count from 1970 yourself.

Filed under Types & casting

The verdict

PostgreSQL, MySQL and SQLite name the operation. SQL Server and Oracle are epoch arithmetic that works but needs discipline about UTC, and SQL Server's int-returning DATEDIFF needs DATEDIFF_BIG for milliseconds.

Where they differ

Unix timestamps (seconds since 1970-01-01 UTC) are the interchange format for everything non-SQL, so each engine offers some path to them. Watch the time zone: only the UTC-based forms are unambiguous.

How each engine writes it

SQL Server

SELECT DATEDIFF(SECOND, '1970-01-01', SYSUTCDATETIME());

Count seconds from the epoch against the UTC clock; GETDATE() would mix local time into the number. DATEDIFF returns int, which runs out in 2038, so use DATEDIFF_BIG for milliseconds or far-future dates.

PostgreSQL

SELECT EXTRACT(EPOCH FROM NOW());

EXTRACT(EPOCH ...) works on timestamps and dates, returning a numeric with fractional seconds. NOW() is time-zone aware, so the result is correct UTC epoch.

MySQL

SELECT UNIX_TIMESTAMP(NOW());

Dedicated function; interprets the input in the session time zone and returns an integer second count.

SQLite

SELECT unixepoch(), STRFTIME('%s', 'now');

unixepoch() (3.38+) returns an integer; STRFTIME('%s', ...) returns the same value as text and works on older versions. 'now' is UTC, and date strings without an offset are read as UTC.

Oracle

SELECT (CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS DATE) - DATE '1970-01-01') * 86400 FROM dual;

No built-in: date subtraction yields days, so multiply by 86400. SYS_EXTRACT_UTC keeps the base UTC.

Questions that come up

Why do I get a local-time epoch on MySQL?

UNIX_TIMESTAMP interprets naive input in the session time zone. If the column stores local wall time, the epoch follows that zone's offset; pin the session zone or store UTC.

How do I get milliseconds?

EXTRACT(EPOCH FROM CLOCK_TIMESTAMP()) * 1000 in PostgreSQL, DATEDIFF_BIG(MILLISECOND, '1970-01-01', SYSUTCDATETIME()) in SQL Server (plain DATEDIFF overflows), UNIX_TIMESTAMP(NOW(3)) * 1000 in MySQL, unixepoch('now', 'subsec') * 1000 in SQLite 3.42+, and SYS_EXTRACT_UTC(SYSTIMESTAMP) arithmetic in Oracle.

Is EXTRACT(EPOCH FROM date) timezone-affected?

From a date or a timestamp without time zone, no: the value is taken at face value as if it were UTC. From timestamptz it converts the instant correctly.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.