Normalize stored timestamps to UTC in SQL
Columns of timestamp-without-time-zone hold UTC clock values. Every display query must attach the zone before converting.
The task
The stored value is UTC wall-clock time with no zone. AT TIME ZONE 'UTC' declares it, and a second AT TIME ZONE renders it in the viewer's zone.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT
created_at,
created_at AT TIME ZONE 'UTC'
AT TIME ZONE 'America/New_York' AS created_eastern
FROM events;
工作原理
On a timestamp without time zone, the first AT TIME ZONE says 'these clock numbers are UTC', producing a timestamptz. The second AT TIME ZONE then renders that instant in New York local time. SQL Server uses the same two-step shape with Windows zone names. Skipping the first step is the usual bug: created_at AT TIME ZONE 'America/New_York' on its own reads the stored value as New York time and converts it to UTC, moving it the wrong way by the offset.
Variations
SQL Server
SQL ServerSELECT
created_at,
created_at AT TIME ZONE 'UTC'
AT TIME ZONE 'Eastern Standard Time' AS created_eastern
FROM events;
Questions that come up
Why does the SQL Server zone name say Standard Time?
Windows zone IDs are historical names like 'Eastern Standard Time', but the conversion still applies daylight saving where the zone observes it. The name is an identifier, not a promise of standard time year-round.
Keep reading
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.