Non-overlap, continuous timestamp ranges (tstzrange) for opening hours

前端 未结 1 1650
失恋的感觉
失恋的感觉 2021-01-06 18:35
CREATE TABLE operating_period (
  id SERIAL NOT NULL PRIMARY KEY,
  during TSTZRANGE NOT NULL,
  -- other meta fields
);

Requirements: 1. No operat

1条回答
  •  执笔经年
    2021-01-06 18:50

    The answer to 1. is clear. To make sure there is no overlap use an exclusion constraint:

    CREATE TABLE operating_period (
      id serial PRIMARY KEY                -- PK is NOT NULL automatically
     ,during tstzrange NOT NULL
     ,EXCLUDE USING gist (during WITH &&)  -- no overlap
    );
    

    This is implemented with a GiST index on during, that supports many types of queries automatically. Related answer:

    • Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL
    • Perform this hours of operation query in PostgreSQL

    Answers to 2. and 3. are not as clear, because it really depends on a lot of things. Both have their pros and cons. For opening hours I would most likely go with range types in current versions of Postgres. I would also enforce [) bounds for all entries to keep things simple. Details in the first linked answer.

    If you should go with (start_at, end_at), you'll be interested in the OVERLAPS operator:

    • Getting results between two dates in PostgreSQL
    • Find overlapping date ranges in PostgreSQL

    Either way, the guideline here is to ask one question per question, not a whole list ...

    0 讨论(0)
提交回复
热议问题