Sub topic 2
Writing Date and Time Literals
Assume you know SELECT, INSERT, and basic type casts. You should also know that UTC is a common reference time and that a UTC offset describes how far a local clock is from UTC.
A date and time literal is a value written directly in SQL. PostgreSQL can often infer its type, but explicit type syntax makes your intention clear and avoids configuration-dependent behavior.
Use ISO-style literals
Prefer the ISO 8601 order: year, month, day. Use a 24-hour clock for times.
SELECT DATE '2024-06-01' AS release_date,
TIMESTAMP '2024-06-01 09:30:00' AS local_meeting,
TIMESTAMPTZ '2024-06-01 09:30:00+02' AS meeting_instant;These three values have different meanings:
datestores a calendar date without a time.timestampmeanstimestamp without time zone. It stores a wall-clock date and time, but no location or offset.timestamptzmeanstimestamp with time zone. It identifies an instant in time.
The +02 offset in the last value tells PostgreSQL how to interpret the input. It identifies the same instant as 07:30:00+00.
You can also write an explicit cast:
SELECT '2024-06-01'::date,
'2024-06-01 09:30:00'::timestamp,
'2024-06-01 09:30:00+02'::timestamptz;The ::type form is PostgreSQL-specific. The type 'value' form is standard SQL and often easier to read.
Avoid ambiguous numeric dates
Inputs such as '06/01/2024' are unsafe because they could mean June 1 or January 6. PostgreSQL's DateStyle setting controls how some ambiguous values are interpreted.
SET DateStyle = 'ISO, MDY';
SELECT '06/01/2024'::date AS mdy_date;
-- 2024-06-01
SET DateStyle = 'ISO, DMY';
SELECT '06/01/2024'::date AS dmy_date;
-- 2024-01-06A session setting can come from a client, connection pool, role, or database configuration. Therefore, do not rely on ambiguous input in application SQL. Use DATE '2024-06-01' or an ISO string with an explicit cast.
Understand offsets and named zones
An offset is not the same as a time zone region. +02 always means two hours ahead of UTC. A named zone such as Europe/Paris includes historical and daylight-saving rules.
A literal can carry a named zone:
SELECT TIMESTAMPTZ '2024-07-01 09:00:00 Europe/Paris' AS paris_instant;PostgreSQL converts the value to an instant internally. The session's TimeZone setting controls how that instant is displayed later.
Exercise
Which literal should you use for an event that starts at 14:00 in New York on March 10, 2024: TIMESTAMP '2024-03-10 14:00:00' or TIMESTAMPTZ '2024-03-10 14:00:00 America/New_York'?
Show answer
Use the timestamptz literal. The named zone lets PostgreSQL apply the applicable offset and identify the event's instant.