2

I am trying to add a new unique index on one of my database tables in SQL Server 2008. This is an existing table and the column where I want the unique index already has some duplicate values.

Can I set up a unique index for that column? If so, how?

5 Answers 5

5

You can't set this column up with a UNIQUE index if the table already has duplicate values, unless you remove the records containing the duplicate values for that column. This goes to the definition of UNIQUE.

Sign up to request clarification or add additional context in comments.

Comments

5

First you are gonna need to delete the duplicate values on your column and then you can create a unique index on it. So lets assume your table has 2 columns, id and column1. To delete duplicate values you need to choose one, it can be random or with some order. So it would be like this:

WITH CTE AS
(
     SELECT *, ROW_NUMBER() OVER(PARTITION BY column1 ORDER BY Id) Corr
     FROM YourTable
)
DELETE FROM CTE
WHERE Corr > 1

CREATE UNIQUE INDEX I_Unique ON YourTable(Column1)

Comments

1

No as the name suggest, Unique Index which says key has to be unique. So you cant

See this

Comments

0

If the column already has duplicate values then I would recommend you create a unique composite key instead.

e.g. So, to handle that issue with this table design, you need to create a unique constraint on the table CustomerID/ProductID columns:

create unique index cust_products_unique on CustomerProducts (CustomerID, ProductID)

So that in essence a combination of fields ensures that the index is unique.

Regards

Comments

0

May not have been true in SQL Server 2008, however you can use Management Studio to do this in later versions such as 2014.

  1. Right click your table
  2. Choose Design
  3. Expand "Identity Specification" and set (is Identity) to Yes
  4. Save

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.