Sub topic 2
Writing Date and Time Literals
A literal is a value written directly in SQL text. PostgreSQL parses date and time literals using the target type, the session DateStyle setting, and (for timestamptz) the session TimeZone setting. This chapter covers how those inputs combine, so that you can write literals that mean the same thing on every connection.
What you need first
This chapter assumes you know basic SQL and can run queries in psql or another client. It also assumes you know what UTC and a UTC offset are. The types themselves (date, time, timestamp, timestamptz, interval) were introduced in the previous chapter. Here the focus is on writing values of those types.
Three ways to write a typed literal
A bare quoted string such as '2024-06-01' has no type of its own. PostgreSQL resolves it from context, for example from the column it is compared with or assigned to. To state the type yourself, use one of three equivalent forms:
SELECT DATE '2024-06-01';
SELECT '2024-06-01'::date;
SELECT CAST('2024-06-01' AS date);All three return 2024-06-01. The TYPE 'string' form is compact and reads well in queries. The :: cast is PostgreSQL-specific, and CAST is standard SQL. Pick one and use it consistently.
An unquoted number is never a date. SELECT DATE 2024-06-01 is a syntax error, and 2024-06-01 without quotes is the integer 2017.
ISO 8601 input
Always write literals in ISO 8601 order: year, month, day, then time. PostgreSQL accepts these forms:
SET TimeZone = 'UTC';
SELECT TIMESTAMPTZ '2024-06-01 09:00:00'; -- 2024-06-01 09:00:00+00
SELECT TIMESTAMPTZ '2024-06-01T09:00:00Z'; -- 2024-06-01 09:00:00+00
SELECT TIMESTAMPTZ '2024-06-01 09:00:00+02'; -- 2024-06-01 07:00:00+00
SELECT TIMESTAMPTZ '2024-06-01 09:00:00+02:00'; -- 2024-06-01 07:00:00+00
SELECT TIMESTAMPTZ '2024-06-01 09:00:00.123456'; -- 2024-06-01 09:00:00.123456+00- The
Tseparator and a trailingZ(UTC) are accepted. - A numeric offset can be
+02,+02:00, or+0200. A positive offset means the local time is ahead of UTC. - Fractional seconds are kept to microsecond (6 digit) precision.
The output of each query above is shown after the -- comment, with the session TimeZone set to UTC.
What an offset does depends on the target type
The same string behaves differently depending on the type you ask for. The diagram shows how PostgreSQL decides.
This has two consequences you should test yourself:
SET TimeZone = 'America/New_York';
-- timestamp: the +02 is dropped without any warning
SELECT TIMESTAMP '2024-06-01 09:00:00+02';
-- 2024-06-01 09:00:00
-- timestamptz with an offset: the offset wins over the session zone
SELECT TIMESTAMPTZ '2024-06-01 09:00:00+02';
-- 2024-06-01 03:00:00-04
-- timestamptz without an offset: the session zone is used
SELECT TIMESTAMPTZ '2024-06-01 09:00:00';
-- 2024-06-01 09:00:00-04The last query is the risky one. Run it on a connection whose TimeZone is UTC and you get a different instant. If a literal has no offset and the type is timestamptz, the result depends on a session setting. Include an offset, or write Z, whenever the instant must be the same everywhere.
DateStyle controls ambiguous input and output
DateStyle has two parts: an output style and an input field order. The default is ISO, MDY. The order matters only for ambiguous strings such as 03/04/2024.
SET DateStyle = 'ISO, MDY';
SELECT DATE '03/04/2024'; -- 2024-03-04 (March 4)
SET DateStyle = 'ISO, DMY';
SELECT DATE '03/04/2024'; -- 2024-04-03 (3 April)
SET DateStyle = 'ISO, DMY';
SELECT DATE '2024-04-03'; -- 2024-04-03 (unambiguous, same under any order)
SET DateStyle = 'SQL, DMY';
SELECT DATE '2024-04-03'; -- 03/04/2024 (output style changed)The same text gives two different dates, and no error is raised. Strings that start with a four-digit year are not ambiguous, which is the main reason to use ISO order.
| Setting part | Affects | Typical values |
|---|---|---|
| Output style | How values are printed | `ISO`, `SQL`, `Postgres`, `German` |
| Field order | How ambiguous input is read | `MDY`, `DMY`, `YMD` |
Client libraries often set DateStyle to ISO on connect so they can parse results. Avoid changing it in application code. If you need a specific display format, use to_char, which a later chapter covers.
Special values
PostgreSQL accepts a few special strings as literals:
SET TimeZone = 'UTC';
SELECT DATE 'infinity'; -- infinity
SELECT DATE '-infinity'; -- -infinity
SELECT TIMESTAMPTZ 'epoch'; -- 1970-01-01 00:00:00+00
SELECT TIMESTAMPTZ 'infinity'; -- infinityinfinity and -infinity compare greater and less than every ordinary value. They are useful as open-ended bounds, such as a row that is valid until further notice.
now, today, tomorrow, and yesterday are also accepted, but they are evaluated when the literal is converted. In a table definition, DEFAULT 'now'::timestamptz is folded into a constant when the table is created, so every row gets the same value. Use DEFAULT now() or DEFAULT CURRENT_TIMESTAMP instead. The next chapters cover the clock functions in detail.
Time-of-day literals, precision, and range limits
Time-only values use the same ISO style:
SELECT TIME '09:30'; -- 09:30:00
SELECT TIME '09:30:15.5'; -- 09:30:15.5
SELECT TIME '24:00:00'; -- 24:00:00
SELECT TIMESTAMP '2024-06-01 24:00:00'; -- 2024-06-02 00:00:0024:00:00 is allowed as the end of a day. In a full timestamp it rolls over to midnight of the next day.
You can limit fractional digits in a column or a cast, such as timestamptz(0) for whole seconds. Extra digits are rounded, not cut off, so '09:00:00.6' cast to precision 0 becomes 09:00:01.
Invalid values raise errors instead of being adjusted:
SELECT DATE '2024-02-30';
-- ERROR: date/time field value out of range: "2024-02-30"
SELECT DATE '2023-02-29';
-- ERROR: date/time field value out of range: "2023-02-29"
SELECT DATE '2024-02-29';
-- 2024-02-29The error comes when the string is parsed. The leap-year rule is applied, so only 2024 has a 29 February.
Interval literals in brief
An interval literal is a duration, not a point in time. You can write it in several styles:
SELECT INTERVAL '1 year 2 months 3 days'; -- 1 year 2 mons 3 days
SELECT INTERVAL '1 day 02:30:00'; -- 1 day 02:30:00
SELECT INTERVAL 'P1Y2M3DT4H'; -- 1 year 2 mons 3 days 04:00:00The P...T... style is ISO 8601 duration syntax. How these values behave in arithmetic is a separate topic.
Literals compared with columns
When you compare a column with a bare string, PostgreSQL converts the string to the column's type:
-- starts_at is timestamptz: '2024-06-01' means midnight in the SESSION zone
SELECT * FROM event WHERE starts_at >= '2024-06-01';
-- explicit offset removes the dependency
SELECT * FROM event WHERE starts_at >= TIMESTAMPTZ '2024-06-01 00:00:00+00';The first query returns different rows on a UTC session than on an America/New_York session. When a query is saved in code, write the type and the offset.
Common errors
- Reading
01/02/2024without knowingDateStyle. The result is silently wrong under the other order. UseYYYY-MM-DD. - Expecting an offset to matter for
timestamp. It is discarded. If the offset matters, the column should betimestamptz. - Leaving the offset off a
timestamptzliteral. The sessionTimeZonefills it in, so results differ between clients. - Using
'now'in a default. Usenow()instead. - Building literals by string concatenation in application code. Pass dates and timestamps as typed query parameters, and let the driver format them.
Exercise
The session TimeZone is 'Asia/Tokyo' (UTC+9, no daylight saving). What does SELECT TIMESTAMPTZ '2024-06-01 09:00:00' return, and what does SELECT TIMESTAMP '2024-06-01 09:00:00+05' return?
Show answer
The first query has no offset, so the Tokyo session zone is used and the result is 2024-06-01 09:00:00+09. The second query targets timestamp without time zone, so the +05 is silently ignored and the result is 2024-06-01 09:00:00.
Exercise
A teammate runs SET DateStyle = 'ISO, DMY'; and then SELECT DATE '05/06/2024';. Which date is returned, and how would you write the literal so the result does not depend on DateStyle?
Show answer
With DMY order the string is read as day 5, month 6, so the result is 2024-06-05. To remove the dependency, write it in ISO order: DATE '2024-06-05'.