Check if new table entry has overlap with existing tables in PostgreSQL

54 Views Asked by At

I'm trying to write a constraint to check whether a new entry in my table has an overlay with already existing entries.

this is my code to add the constraint which doesnt work:

ALTER TABLE tour
    ADD CONSTRAINT UC_tour
    CHECK (SELECT 1
    FROM tour t2 
    WHERE (tour.starting_time, tour.starting_time + tour.duration) NOT OVERLAPS (t2.starting_time, t2.starting_time + t2.duration)
    )

The table looks like this:

CREATE TABLE tour (
  id  INTEGER,
  Starting_Time TIME,
  Duration      INTERVAL,
  Price         NUMERIC,
  Weekday       DATE,
  PRIMARY KEY (id)

It should not let me add new entries with an overlapping tour time

0

There are 0 best solutions below