How do you handle date and time values in SQL?

Instruction: Discuss the data types and functions used for managing date and time values in SQL.

Context: This question tests the candidate's proficiency with SQL's temporal data handling, which is crucial for many applications.

Updated

Official answer

Choose types by meaning. In PostgreSQL, date stores a calendar date; time stores a time of day; timestamp without time zone stores a local date/time without identifying an instant; timestamptz represents an instant displayed in the session zone. Timestamptz does not preserve the original named zone, so store that separately when needed.

To select events on a Los Angeles calendar day from events(event_id integer, occurred_at timestamptz):

SELECT event_id
FROM events
WHERE occurred_at >= TIMESTAMP '2026-03-08 00:00:00' AT TIME ZONE 'America/Los_Angeles'
  AND occurred_at <  TIMESTAMP '2026-03-09 00:00:00' AT TIME ZONE 'America/Los_Angeles'
ORDER BY event_id;

This half-open interval uses local midnight boundaries; that daylight-saving transition day spans 23 elapsed hours. Do not assume every local day is 24 hours or mix functions from different SQL dialects. Specify timezone, precision and ambiguous-time policy, and test boundaries, leap days and missing timestamps. An index on occurred_at may help the range query depending on the workload.

Related Questions