Skip to content
Advertisement

Postgres trigger to check date overlap with already existing records

I have a table which have 2 column, start date and end date.

  • start date is required
  • end date is optional (so it’s a period that basically never ends)

I’m creating a trigger which ensure that no record overlap with the other ones, and so far I made this

You can see that I’m testing all the overlap conditions one by one, the problem about a non-ending period I solved using a date up to year 9999, to make all working.

This code I’m sharing it’s working, at the end of it you cand find a insert statement which ends with failure (related to the given case),

Those checks are a lot “manually”, I’m wondering if this can be achieved with a query which uses intersect or similar but I haven’t find a working approach


EDIT Based on @GMB approach, this is the final result

In my actual scenario I also have a column which defines if the record is active or not, so I added a where clause in the definition. I also moved to a separate ADD CONSTRAINT statement because my table already exists, so I only add this one.

Advertisement

Answer

No need for complicated trigger code. You can do what you want simplify and efficiently with an exclusion constraint:

Argument [] to daterange() makes the range inclusive on both ends, which is how I understood your question.


Edit: if you want the exclusion to be based on another column, say user_id:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement