// dates & times reference

SQL EXTRACT epoch function

Returns a timestamp as seconds since 1970-01-01, or an interval as its total length in seconds.

カテゴリ
Dates & times
Returns
numeric (double precision before PostgreSQL 14)
In this category
52 of 121

構文

EXTRACT(epoch FROM ts)
EXTRACT(epoch FROM interval '1 day')  -- 86400

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

エンジンサポート

エンジンSupportメモ
SQL Server Different name or syntax DATEDIFF_BIG(second, '1970-01-01', ts)
PostgreSQL はい Supported under this name.
MySQL Different name or syntax UNIX_TIMESTAMP(ts)
SQLite Different name or syntax strftime('%s', ts)
Oracle Different name or syntax date subtraction times 86400

例

PostgreSQL

SELECT EXTRACT(epoch FROM created_at)::bigint AS epoch FROM orders;

PostgreSQL

SELECT EXTRACT(epoch FROM SUM(end_ts - start_ts)) AS total_seconds FROM shifts;

MySQL

SELECT UNIX_TIMESTAMP(created_at) AS epoch FROM orders;

知っておくと便利なこと

  • A timestamp without time zone is counted as if it were UTC, whatever the session zone; a timestamptz gives the true instant. Storing local wall time in a plain timestamp therefore shifts every epoch by your UTC offset.
  • On intervals, months and years are fixed lengths: EXTRACT(epoch FROM interval '1 month') is 2,592,000 (30 days) and '1 year' is 365.25 days.
  • The return is numeric (double precision before PostgreSQL 14); cast to bigint for clean API responses.

Questions about EXTRACT(epoch)

What is the difference between EXTRACT(epoch) and UNIX_TIMESTAMP?

Spelling and engine: PostgreSQL uses EXTRACT(epoch FROM ts), MySQL uses UNIX_TIMESTAMP(ts). Same seconds-since-1970 result.

Why does one month give 30 days?

An interval has no start date, so PostgreSQL converts a month to 30 days and a year to 365.25 days. For an exact span, subtract two real timestamps and extract the epoch from that.

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

// 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.