0

How can I add DB level unique constraint to a column in a table in Rails using its migration? I googled but those answer seems to involve index, and I don't want to touch index because I'm not sure if it will have bad side effect (because stackoverflow.com/a/3370333/6359753 has a comment saying it will have storage influence). Do I must have it and will it have bad side effect?

This is why even though I have read A migration to add unique constraint to a combination of columns but still asking this question.

2
  • " I don't want to touch index because I'm not sure if it will have bad side effect". What side effect are you anticipating? The answer you referenced should work for you... Commented Jul 31, 2018 at 3:39
  • stackoverflow.com/a/3370333/6359753 has a comment saying it will have stroage influence Commented Jul 31, 2018 at 4:34

1 Answer 1

1

Yes, the unique index is a necessary part of a unique constraint: the index is how the constraint is enforced [efficiently].

Creating a unique index on its own doesn't always technically create a constraint, but that is almost always an irrelevant distinction.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this is really helpful, but I'm concerning about the part where you said "Creating a unique index on its own doesn't always technically create a constraint". If I do add_index :my_table, :my_column, unique: true, will that guarantee my my_column values to be all unique to each other?
Yes, it will. Be less concerned: you're doing a simple common thing, and the popular answer will do what you want.
Thank you, that's all I need to know for now. For the technical part, can you point me to some resource for further reading?

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.