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

1

6
CREATE TABLE operating_period (
  id SERIAL NOT NULL PRIMARY KEY,
  during TSTZRANGE NOT NULL,
  -- other meta fields
);

Requirements: 1. No operating period can overlap with each other

Question:

  1. How do I add a constraint to make sure that there is no overlap in the operating hours?
  2. In terms of query speed, am I better off with two columns (start_at, end_at) or is GIST index fast for tstzrange?
  3. In schema design, is tstzrange commonly used? Or am I better of with two columns?
Schilit answered 23/10, 2014 at 23:35 Comment(0)
P
13

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. See:

Answers to 2. and 3. are not as clear because those really depend on a lot of things. 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:

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

Pecoraro answered 24/10, 2014 at 1:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.