sqlsql-servert-sqlsql-server-2014

How to ensure that there are no duplicates in field? MS SQL Server 2014


I have the following table:

Customer (Id, Name, employeeID)

The table is already created and is empty, I don't want to remove duplicate data, all I want is to ALTER the table to ensure that there will be no duplicate data

I want to use ALTER and ensure that there are no duplicates in employeeID.

Will

ALTER TABLE Customers
UNIQUE(employeeID)
ADD CONSTRAINT

Is there a better way?


Solution

  • Adding a unique constraint will ensure that no duplicate entries will be added in future:

    ALTER TABLE Customers
    ADD CONSTRAINT choose_a_name_for_the_constraint UNIQUE (EmployeeID);   
    

    You had it basically right, just a bit of a keyword order problem..

    If you're working with SQLS, consider also that trivial operations like this can be done via the GUI in SSMS, and it will guide the process. You can also get it to turn the changes into scripts for you by right clicking the table and choosing "Script Table As..." so you can use them elsewhere