SQL Server 2005 How Create a Unique Constraint?

David Basarab picture David Basarab · Sep 15, 2008 · Viewed 182.6k times · Source

How do I create a unique constraint on an existing table in SQL Server 2005?

I am looking for both the TSQL and how to do it in the Database Diagram.

Answer

Rory picture Rory · Sep 15, 2008

The SQL command is:

ALTER TABLE <tablename> ADD CONSTRAINT
            <constraintname> UNIQUE NONCLUSTERED
    (
                <columnname>
    )

See the full syntax here.

If you want to do it from a Database Diagram:

  • right-click on the table and select 'Indexes/Keys'
  • click the Add button to add a new index
  • enter the necessary info in the Properties on the right hand side:
    • the columns you want (click the ellipsis button to select)
    • set Is Unique to Yes
    • give it an appropriate name