3

I have the following constraint:

ALTER TABLE my_table
  ADD CONSTRAINT no_overlap EXCLUDE USING gist (
    product_id WITH =,
    applicable_period WITH &&
  )

Now I realized, that this should only be checked conditionally, e.g.

ALTER TABLE my_table
  ADD CONSTRAINT no_overlap EXCLUDE USING gist (
    product_id WITH =,
    applicable_period WITH &&
  )
  WHERE my_table.user_id IS NULL

Is this possible and otherwise how can I achieve this in an efficient/advised way? (I could add a trigger, but I hope there is more elegant/efficient approaches).

Should I resort to table partition? Thank you

3
  • Exclusion constraints prevent 2 rows from having overlapping values - you declare a list of comparisons and at least one of them should evaluate to FALSE or NULL. So you could simply add user_id WITH = to your constraint definition. Commented Apr 29, 2020 at 13:54
  • but wouldn't it be "broken" because NULL is not equal to NULL? Commented Apr 29, 2020 at 14:10
  • @IVOGELOV that would indeed allow overlapping ranges for rows without a user_id. But it would also allow overlapping ranges for different users - which the filtered version wouldn't. Commented Apr 29, 2020 at 14:16

1 Answer 1

6

According to the manual, you simply need parentheses:

ALTER TABLE my_table
  ADD CONSTRAINT no_overlap 
  EXCLUDE USING gist (product_id WITH =, applicable_period WITH &&)
WHERE (user_id is null);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.