Question

So here's what I'm trying to do:

I have a number of events, each event represents a datetime range (like 07.03.2014 06:00 - 07.03.2014 08:00) event is associated (one-to-many) to hall_schedule.

Then I want to search for all hall_schedule's that don't have events that cover some specific time range, for example:

"I want all hall_schedules where hall events don't cover the 07.03.2014 06:00 - 07.03.2014 08:00 range"

So the question is, in order to get the best performance, how do I design this? What is the best way to store events and later do the described search?

I'd be glad to use something specific to postgresql (9.3), whatever would give the best performance

Was it helpful?

Solution

  1. use TIMESTAMP WITH TIME ZONE for hall_schedule's start and end time points
  2. use tstzrange to detect overlappings, like:

    SELECT *
      FROM "hall_schedule"
     WHERE NOT (tstzrange("start", "end", '[]') &&
                tstzrange(:input_start, :input_end, '[]'))
    

Notes:

  • you could store the whole range in a tstzrange column within the hall_schedule table, if you want, but it's harder to edit from the application (you must supply its text representation everywhere)
  • this way, you can actually create EXCLUDE constraints too, to prevent events in hall_schedule to overlap each other, if you want.

Update:

Additionally, to speed up your queries, you can add the following index too:

CREATE INDEX "hall_schedule_range_idx"
          ON "hall_schedule"
       USING gist ((tstzrange("start", "end", '[]')));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top