1

I am having a table with two columns. Want to add unique constraint on both columns. One of the column is nullable.

I m trying with this syntax:

ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, (coalesce(a_name, '')));

Its prompting error at or near "("

2
  • m confused, why are you using coalesce?? also if possible please confirm the db server you are using newer sql(2008+) server allows you to create Unique constraints with where clause which can be then used conditionally. Commented Dec 7, 2017 at 5:38
  • Create partial constraint(Refer - stackoverflow.com/questions/8289100/…) Commented Oct 9, 2019 at 11:44

1 Answer 1

-3

You don't need to use coalesce in that case. Just create constraint in the usual way:

ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, a_name);
Sign up to request clarification or add additional context in comments.

3 Comments

actually one of his column is nullable that's why I think he tried to use coalesce. I think your query will not work in this scenario as it will not allow more that on null values
Why do you think that the constraint will not allow more than one NULL value?
@BlindSniper: if that was the case (which it isn't) then coalesce() would actually do the wrong thing as you replace null with '' which indeed means you can have only one combination of a_id and a null value. without coalesce you can add (1,null), (1,null) but with coalesce that would be turned into putting (1,'') into the index and that will only be allowed once

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.