Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Unique index vs Unique constraint - Re. Duplicate values

A unique index ensures that the values in the index key columns are unique. A unique constraint guarantees that no duplicate values can be inserted into the column(s) on which the constraint is created. When a unique constraint is created a corresponding unique index is automatically created on the column(s).

Questions:

  1. Can duplicate values be inserted if we have a unique index on a column and no unique constraint?
  2. What about existing duplicates in any on the column - will it allow to create unique index or unique constraint?
like image 566
variable Avatar asked Mar 12 '26 22:03

variable


2 Answers

Can duplicate values be inserted if we have a unique index on a column and no unique constraint?

Generally, duplicate values cannot be inserted and an error is raised when a unique index exists on the column. The exceptions are:

  1. Index was created with the IGNORE_DUP_KEY option. No error is raised and the insert is ignored.

  2. The non-clustered index is filtered such that the duplicate value does not satisfy the index WHERE clause. The row is inserted but not reflected in the non-clustered index.

What about existing duplicates in any on the column - will it allow to create unique index or unique constraint?

No, with the exception of the filtered index mentioned above.

like image 127
Dan Guzman Avatar answered Mar 15 '26 12:03

Dan Guzman


One potentially unintuitive scenario that confused me at first: postgres does not treat NULL values as equal. If your table looked like this:

+-------+-------+-------+
|id     |a      |b      |
+-------+-------+-------+
|1      |0      |NULL   |
|2      |0      |NULL   |
+-------+-------+-------+

You could still add a unique index on columns a and b. According to Postgres, row with id 1 and row with id 2 have the same value for column a, but different values for column b

like image 39
Pearce Merritt Avatar answered Mar 15 '26 12:03

Pearce Merritt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!