user161433 user161433 - 1 year ago 84
SQL Question

What is the Point of using a Unique index on a Guid Column

Since, guid values will always be unique anyway why use a unique index. Isnt it true that when you use a unique index that it slows down inserts?

Answer Source

Uses of UNIQUE constraints:

  • Enforcing uniqueness. Although a generated GUID is very likely to be unique, you could easily insert the same GUID in multiple rows. Of course you could do it by mistake, but this may even be part of your design, for instance for compound key constraints in many-to-many tables.

    CREATE TABLE BookAuthors (
      guid INT PRIMARY KEY,
      BookGuid INT NOT NULL,
      AuthorGuid INT NOT NULL,
      FOREIGN KEY (BookGuid) REFERENCES Books(BookGuid),
      FOREIGN KEY (AuthorGuid) REFERENCES Authors(AuthorGuid),
      UNIQUE KEY (BookGuid, AuthorGuid)
  • Being the target of a foreign key. You probably are accustomed to FOREIGN KEY referencing a PRIMARY KEY of the parent table. Did you know that a FOREIGN KEY can also reference a UNIQUE KEY?

    CREATE TABLE Acknowledgements (
      guid INT PRIMARY KEY,
      BookGuid INT NOT NULL,
      AuthorGuid INT NOT NULL,
      Acknowledged VARCHAR(100) NOT NULL,
      -- this works because of the UNIQUE constraint in BookAuthors:
      FOREIGN KEY (BookGuid, AuthorGuid) 
        REFERENCES BookAuthors (BookGuid, AuthorGuid)
  • Performance. UNIQUE is a constraint, as others have pointed out, but in most brands of database, an index is implicit when you define a UNIQUE, PRIMARY KEY, or FOREIGN KEY constraint. You're right that there's some overhead when inserting to any indexed table, but the performance benefit of an index is a net win, usually many times over.

  • Uniqueness notwithstanding NULL. While the primary key is crucial for the use of identifying a rows in a table, they don't permit NULLs. You can use UNIQUE constraints to enforce uniqueness in nullable columns.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download