Search code examples
mysqlsqlindexingrdbmsdatabase-performance

Indexing and constraints for uniqueness/relationship with primary key


I need to clear the following in my head.

When I create a table with no primary key or unique constraint I get a flat file.
When I create a primary key a primary index is created as a result and it is this index that maintains the uniqueness of the primary key, right? So I can not add a duplicate value.
So if I create an index on any column does this enforce the column to have unique values? Or that depends on using the keyword UNIQUE for the index creation?
Finally every time I declare a column having a UNIQUE constraint does that mean that an index is created and so these actions are interchangeable?


Solution

    1. If we create an index on any column, that does not enforce that a column to have unique values. There can be duplicate values in the column, but those will be indexed.
    2. Unique values in column will be enforced by using the keyword UNIQUE for the column.
    3. The differences between UNIQUE column and Primary key column is - UNIQUE key column can hold NULL value in one and only one of the table row. Primary key column will not hold null value.
    4. When a UNIQUE column is created, then implicitly an index is created. But when an Index is created on a column that does not mean all the row value for the column will be UNIQUE. So they are not interchangeable.