Sub topic 1
The date and time types and when to use each
PostgreSQL has five date and time types, and choosing between them is the first decision in any schema that stores time. A wrong choice often goes unnoticed until the data crosses a time zone or a daylight saving change. This chapter covers what each type holds, how much space it takes, and which kind of fact each one fits.
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL:
SELECT,WHERE,GROUP BY,INSERT, andCREATE TABLE. - Run queries in
psqlor another SQL client. - Explain roughly what UTC and a UTC offset are, for example that
+02means two hours ahead of UTC.
Later chapters cover time zone conversion, intervals, and range queries in detail. Here we only name those ideas where they affect the choice of type.
The five types at a glance
| Type | Holds | Storage | Resolution | Range |
|---|---|---|---|---|
| `date` | A calendar day | 4 bytes | 1 day | 4713 BC to 5874897 AD |
| `time` (without time zone) | A time of day | 8 bytes | 1 microsecond | 00:00:00 to 24:00:00 |
| `timestamp` (without time zone) | A calendar day plus a time of day | 8 bytes | 1 microsecond | 4713 BC to 294276 AD |
| `timestamptz` (`timestamp with time zone`) | A single instant on the timeline | 8 bytes | 1 microsecond | 4713 BC to 294276 AD |
| `interval` | A length of time | 16 bytes | 1 microsecond | plus or minus 178,000,000 years |
PostgreSQL also has timetz (time with time zone, 12 bytes). The PostgreSQL documentation discourages it, and the reason is given below.
You can ask PostgreSQL which type an expression has with pg_typeof:
SELECT pg_typeof(DATE '2024-06-01') AS d,
pg_typeof(TIME '09:30') AS t,
pg_typeof(TIMESTAMP '2024-06-01 09:30') AS ts,
pg_typeof(TIMESTAMPTZ '2024-06-01 09:30+00') AS tstz,
pg_typeof(INTERVAL '2 hours') AS iv;
-- d: date
-- t: time without time zone
-- ts: timestamp without time zone
-- tstz: timestamp with time zone
-- iv: intervalTwo kinds of facts
Most of the choice comes down to whether you are recording something that happened at a moment in the world or something written on a calendar or clock face.
- An instant is a point on the timeline that is the same for everyone. A payment was captured at one instant. A server logged an error at one instant. People in different time zones would read different clock times for it, but they agree it is one moment.
- A civil time (also called wall-clock time) is what a clock or calendar shows, with no claim about which instant it is. "Shops open at 09:00" and "birthday is 14 March" are civil times. They mean something different in each place.
timestamptz models instants. date, time, and timestamp model civil times. interval models a duration and fits neither category.
When to use each type
timestamptz: the default for events
Use timestamptz for anything that records or schedules a real moment: creation times, log entries, orders, logins, meetings, and deadlines. The name is misleading because the type does not store a time zone. It stores an instant, and the session's TimeZone setting controls how the instant is displayed. The next chapters explain this in detail. For now, remember that two clients in different zones can read the same row and both be correct.
timestamp: civil time without an instant
timestamp stores a day and a time with no zone attached. It is the right type when the value really is a wall-clock reading that you do not want anchored to an instant. Examples are "the 2025 conference starts at 2025-05-12 09:00 local time at the venue" when the venue's zone is stored separately, or an intermediate result after you convert an instant into a particular zone.
The danger is that timestamp silently drops any offset you supply:
SELECT TIMESTAMP '2024-06-01 09:00:00+02' AS ts,
TIMESTAMPTZ '2024-06-01 09:00:00+02' AT TIME ZONE 'UTC' AS tstz_in_utc;
-- ts: 2024-06-01 09:00:00
-- tstz_in_utc: 2024-06-01 07:00:00The first value discards the +02, so the value now means nothing definite about when it happened. If your data came from several zones, a plain timestamp column cannot tell you which came first.
date: whole days
Use date for facts that are about a day and carry no time: birth dates, invoice dates, holidays, and report dates. It uses 4 bytes, half of a timestamp. Subtracting two dates gives a whole number of days:
SELECT DATE '2024-03-01' - DATE '2024-02-01' AS days_between;
-- 29Do not store a day as a midnight timestamptz to "be safe". Midnight in one zone is a different instant in another, and a day boundary shifts with the zone. A date states the intent correctly.
time: a time of day
Use time for a recurring clock time that has no date, such as a shop's opening time or an alarm. Values run from 00:00:00 to 24:00:00. It cannot express a duration of more than a day, so use interval for that.
timetz attaches a fixed offset to a time of day. An offset such as +02 does not say whether daylight saving applies, and a time of day without a date cannot be resolved to a rule-based zone. The documentation notes the type exists for SQL compliance and recommends against it. If you need a time of day in a zone, store a time and a separate zone name, then combine them with a date when you need an instant.
interval: durations
Use interval for lengths of time such as a subscription term, a task duration, or a timeout. Internally an interval holds three separate parts: months, days, and microseconds. That is why 1 month, 30 days, and 720 hours are different values. Later chapters show how this affects date arithmetic across month ends and daylight saving changes.
Subtracting two timestamps produces an interval:
SELECT TIMESTAMP '2024-03-01 12:00' - TIMESTAMP '2024-02-29 00:00' AS elapsed;
-- 1 day 12:00:00Precision and special values
Each of time, timestamp, timestamptz, and interval accepts an optional precision p from 0 to 6, which is the number of fractional-second digits kept. The default keeps microseconds. A lower precision rounds the value rather than truncating it:
SELECT TIMESTAMP(0) '2024-06-01 09:00:00.789' AS rounded;
-- 2024-06-01 09:00:01Rounding can carry into a higher unit, as it did here. Choose the precision when you design the column if you want stable results, for example timestamptz(3) for millisecond data.
date, timestamp, and timestamptz also accept the special values infinity and -infinity. These are useful as open-ended bounds, such as a valid_until column that means "no end date":
SELECT 'infinity'::timestamptz > TIMESTAMPTZ '9999-12-31 00:00:00+00' AS is_later;
-- tRemember that they are not real moments, so arithmetic on them yields infinity or an error rather than a useful number.
Combining types
Types mix according to rules you can usually predict. Adding a time to a date gives a timestamp, and adding an interval to a date also gives a timestamp:
SELECT DATE '2024-06-01' + TIME '09:30' AS date_plus_time,
DATE '2024-06-01' + INTERVAL '2 hours' AS date_plus_interval;
-- date_plus_time: 2024-06-01 09:30:00
-- date_plus_interval: 2024-06-01 02:00:00Adding an integer to a date adds days and keeps the type date. These rules matter later, because the output type of a calculation tells you whether the result has a time zone meaning.
A worked schema
This table uses each type for the kind of fact it fits:
CREATE TABLE appointment (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
birth_date date,
starts_at timestamptz NOT NULL,
duration interval NOT NULL DEFAULT INTERVAL '30 minutes',
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO appointment (customer, birth_date, starts_at)
VALUES ('Ada', DATE '1990-03-14', TIMESTAMPTZ '2024-06-01 09:00:00+02');
SELECT customer, starts_at + duration AS ends_at
FROM appointment;
-- Ada | 2024-06-01 07:30:00+00 (when the session TimeZone is UTC)The birth date is a date because it is a calendar fact. The appointment start is a timestamptz because it is a real moment. The duration is an interval because it is a length. The end time is computed, not stored, so it cannot drift out of sync with the other columns.
Summary of choices
- Moment that is real for everyone:
timestamptz. - Calendar day:
date. - Clock reading with no instant meaning:
timestamportime. - Length of time:
interval. - Avoid
timetz.
Exercise
A table records when users signed up, each user's birthday, and how long each user's free trial lasts. Name the best type for each column and give one reason for the signup column.
Show answer
Signup time is timestamptz, birthday is date, and trial length is interval. Signup is a real moment that all users share, so it needs an instant type. The same stored value then displays correctly in any session time zone.
Exercise
What does SELECT TIMESTAMP '2024-06-01 09:00:00+05' return, and why can that be a problem for event data?
Show answer
It returns 2024-06-01 09:00:00. The type timestamp ignores the +05 offset, so the value no longer identifies which instant it was. Events entered from different zones cannot be ordered reliably.
Exercise
What type is the result of DATE '2024-03-10' - DATE '2024-03-01', and what is its value?
Show answer
The result is an integer, 9, which is the number of days between the two dates. It is not an interval.