Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent date overlap postgresql

Is there a way to add a constraint to a postgresql table to prevent dates overlapping? For example, I have a table called workouts that has date columns week_start, week_end. I want to make sure that none of the week_start - week_end ranges overlaps with any existing ranges. HOWEVER, the end date of week_start can overlap with the start date of week_end.

Can someone help?

Thanks in advance!

like image 895
Trung Tran Avatar asked Jun 13 '16 13:06

Trung Tran


2 Answers

You can do this with an exclusion constraint, using the overlap operator (&&) for the daterange type:

CREATE TABLE workouts (
  week_start DATE,
  week_end DATE,
  EXCLUDE USING gist (daterange(week_start, week_end) WITH &&)
)
like image 60
Nick Barnes Avatar answered Oct 10 '22 09:10

Nick Barnes


You can add an EXCLUDE table constraint to your table definition and then work with ranges to detect overlaps. This would work really nice if you can change your table definition to turn columns week_start and week_end into a single range, say weeks.

CREATE TABLE workouts (
  ...
  weeks   intrange
  EXCLUDE USING gist (weeks WITH &&)
);
like image 35
Patrick Avatar answered Oct 10 '22 10:10

Patrick