// SQL snippet

Convert between Unix epoch and timestamps in SQL

APIs and queues speak Unix seconds; databases speak their own timestamp types. Both directions of the bridge are needed constantly.

Main statement
PostgreSQL
다음도 지원
SQL Server MySQL

The task

extract(epoch) reads a timestamp as epoch seconds; to_timestamp builds one back from seconds.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT
    extract(epoch FROM occurred_at)::bigint AS epoch_seconds,
    to_timestamp(1787500000) AS from_epoch
FROM events;

작동 방식

extract(epoch FROM timestamptz) counts true elapsed seconds since 1970-01-01 UTC, so it is DST-proof and orderable; on a plain timestamp PostgreSQL treats the value as UTC. to_timestamp reverses it and returns a timestamptz: to_timestamp(1787500000) is 2026-08-23 15:46:40 UTC, displayed in the session's zone. Milliseconds need a 1000 factor in both directions; keep the unit in the column name or someone will assume seconds.

Variations

MySQL (interprets DATETIME in the session time_zone)

MySQL
SELECT
    UNIX_TIMESTAMP(occurred_at) AS epoch_seconds,
    FROM_UNIXTIME(1787500000) AS from_epoch
FROM events;

SQL Server (DATEDIFF_BIG avoids the 2038 int overflow)

SQL Server
SELECT
    DATEDIFF_BIG(SECOND, '1970-01-01 00:00:00', occurred_at) AS epoch_seconds,
    DATEADD(SECOND, 1787500000, '1970-01-01 00:00:00') AS from_epoch
FROM events;

Questions that come up

Why did my epoch round-trip land an hour off?

Usually a session time zone got involved. MySQL's UNIX_TIMESTAMP and FROM_UNIXTIME read and write DATETIME values in the session time_zone, so run SET time_zone = '+00:00' when the column holds UTC. On PostgreSQL, casting to_timestamp's timestamptz result to a plain timestamp applies the session zone; use AT TIME ZONE 'UTC' instead. SQL Server's DATEDIFF from '1970-01-01' has no zone at all, so it is only right if occurred_at holds UTC.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.