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.

Henry Yang
  • 2,283
  • 3
  • 21
  • 38
  • " 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... – Mark Merritt Jul 31 '18 at 03:39
  • https://stackoverflow.com/a/3370333/6359753 has a comment saying it will have stroage influence – Henry Yang Jul 31 '18 at 04:34

1 Answers1

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.

matthewd
  • 4,332
  • 15
  • 21
  • 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? – Henry Yang Jul 31 '18 at 06:16
  • 1
    Yes, it will. Be less concerned: you're doing a simple common thing, and the popular answer will do what you want. – matthewd Jul 31 '18 at 06:18
  • 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? – Henry Yang Jul 31 '18 at 07:16