Why does INDEX creation statement have UNIQUE argument?
As I understand, the non-clustered index contains a bookmark, a pointer to a row, which should be unique to dist
While a non-unique index is sufficient to distinguish between rows (as you said), the UNIQUE
index serves as a constraint: it will prevent duplicates from being entered into the database - where "duplicates" are rows containing the same data in the indexed columns.
Example:
Firstname | Lastname | Login
================================
Joe | Smith | joes
Joe | Taylor | joet
Susan | Smith | susans
Let's assume that login names are by default generated from first name + first letter of last name.
What happens when we try to add Joe Sciavillo to the database? Normally, the system would happily generate loginname joes
and insert (Joe,Sciavillo,joes)
. Now we'd have two users with the same username - probably a Bad Thing.
Now let's say we have a UNIQUE
index on Login
column - the database will check that no other row with the same data already exists, before it allows inserting the new row. In other words, the attempt to insert another joes
will be rejected, because that data wouldn't be unique in that row any more.
Of course, you could have unique indexes on multiple columns, in which case the combination of data would have to be unique (e.g. a unique index on Firstname,Lastname
will happily accept a row with (Joe,Badzhanov)
, as the combination is not in the table yet, but would reject a second row with (Joe,Smith)
)