Handling dates and times in SQL queries with PostgreSQL

(mon-code.net)

13 points | by metfan 3 days ago

3 comments

  • flossly 2 hours ago
    Lame article tbh.

    It's better to use `timestampz` everywhere; the author seems to know but then uses `timestamp`...

    Most of the functions showcased one will not need as one will do that in the app-layer or even in the frontend code.

    • LittleLily 1 hour ago
      Given that most people will be doing most of the time functions in their application code anyway like you said, why would it not be better to just use `timestamp` everywhere then? They both store the same data and the only difference is that `timestamptz` adds an unnecessary conversion on read and write operations (which also changes based on the system's timezone) that you should be doing in your application anyway.
      • n_e 8 minutes ago
        Some reasons would be to document what is stored in the column and make it convenient to do interactive queries.

        Otherwise we could go even further than timestamp and store the unix time in a bigint column.

      • epgui 1 hour ago
        Your data at rest is meaningless unless it represents a point in time. You can’t generally compare timestamps or filter by > or < or do any date arithmetic, unless you have points in time or other implicit guarantees (eg.: all of the timestamps are relative to the same time zone, there is no DST, and no historical time adjustments).

        When you get into the weeds, it’s almost impossible to correctly use.

        • LittleLily 53 minutes ago
          but `timestamptz` doesn't solve that. it doesn't store a timezone for you. it's still on you to turn the raw timestamp into an actual point in time by enhancing it with timezone/offset data, it's just a question of whether you rely on that extra data coming from your system's configured timezone (which is what `timestamptz` does every time you read the value), or something your application decides.
  • ruslanty 3 days ago
    For reports by local date, I’d convert both local midnights to timestamptz separately, then filter with ts >= start AND ts < end. If you take the first midnight and just add 24 hours, you can miss an hour or pull in an hour from the next day when the clocks change
  • traceroute66 2 hours ago
    Interesting site, but its missing some of the more advanced things you can do in Postgres like `EXCLUDE USING gist` to prevent overlapping schedules.