1

Hi there I hope anyone can help me.

lets say that I have on my table the following

name text startTime timestamp without time zone endTime timestamp without time zone

here is what I am trying to do:

I am trying to check if the time that is about to be added to the database will overlap the time that is already on the table.

sample:

name            startTime               endTime
---------|------------------------|----------------------
tommy    |   2019-07-10 08:30:00  |   2019-07-10 10:30:00
tommy    |   2019-07-10 10:31:00  |   2019-07-10 11:30:00  
tommy    |   2019-07-10 07:30:00  |   2019-07-10 09:00:00 <=== if I click enter to enter this tird schedulle for this user, the sistem will give me a conflict message because this user already has a schedulle that start from 2019-07-10 08:30:00 to 2019-07-10 10:30:00 on our first row of the table.

As for my codes to insert on the database all I have is this simple php

$sql = "insert into horarios (name, startTime, endTime) values ('$name', '$startTime', '$endTime');";
$res = @pg_query ($con, $sql);
if ($res == NULL){
    echo "Query failed.";
    exit (0);
}
GMB
  • 216,147
  • 25
  • 84
  • 135

1 Answers1

3

Let the database do the heavy lifting! You can use timestamp ranges and an exclusion constraint to prevent insertion of overlapping date ranges:

alter table horarios
    add constraint horarios_range_overlap
    exclude using gist (tsrange(startTime, endTime) with &&)

The database uses the timestamps as bounds to build a tsrange, and then ensures that there is no overlap, using operator &&. Conflicting records are rejected.

By default, the timestamp range is inclusive on the lower bound and exclusive at the upper bound - but this can be modified.

GMB
  • 216,147
  • 25
  • 84
  • 135
  • it works, but it gives me a error if I have to add another schedule for a different name. Sample if I add (tommy 2019-07-10 08:30:00 2019-07-10 10:30:00) for the next user gives me error if I add (john 2019-07-10 08:30:00 2019-07-10 10:30:00) it only works if the time for John starts from 10:30:00. How can I make it work ? –  Sep 07 '20 at 07:54