I see add_index ~ unique: true
statement in schema.rb
and think uniqueness is constraint for table, not for index.Using index is one of way realizing uniqueness, Programmer should not designate to the RDBMS "how" and index quicken searching but take costs inserting. In fact, is there another way to keep uniqueness constraint? If not, why Rails provide us only add_index
statement for uniqueness constraint?
Because there is no need for other ways. Under the hood it's all the same: when you define a UNIQUE
constraint, a UNIQUE
index is created on that table to enforce it.
Question from DBA.SE: When should I use a unique constraint instead of a unique index?
So for a database that supports both features the choice of which to use will often come down to preferred style and consistency.
So using indexes everywhere in Rails is consistent. That's the reason.
A cite from PostgreSQL's docs:
PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.
I haven't found the related cite for MySQL in an authoritative source, but "rumors are everywhere".