Jp_
Jp_

Reputation: 6183

Verifying the unity of period of time in SQL

I have a table in the format

CREATE TABLE TimePeriod(
    startTime integer NOT NULL, 
    endTime integer NOT NULL, 
    otherData TEXT
)

and I need to be sure that there's no overlapping between periods of time.

Example:

Obs: I'm using SQLite and I'm storing the time as seconds since midnight, I can change the table structure if needed.

Upvotes: 0

Views: 51

Answers (1)

CL.
CL.

Reputation: 180070

CHECK constraints may not contain a subquery, so you have to use a trigger.

To prevent a row from being inserted, the trigger must evaluate the RAISE function. The WHERE filter prevents this when no other row with an overlapping time is found:

CREATE TRIGGER prevent_overlapping_time
BEFORE INSERT ON TimePeriod
FOR EACH ROW
BEGIN
    SELECT RAISE(ABORT, 'overlapping time')
    FROM TimePeriod
    WHERE NEW.endTime > startTime
      AND NEW.startTime < endTime;
END;

Upvotes: 1

Related Questions