Share via


Create Unique Constraints

You can create a unique constraint in SQL Server 2014 by using SQL Server Management Studio or Transact-SQL to ensure no duplicate values are entered in specific columns that do not participate in a primary key. Creating a unique constraint automatically creates a corresponding unique index.

In This Topic

Before You Begin

Security

Permissions

Requires ALTER permission on the table.

Using SQL Server Management Studio

To create a unique constraint

  1. In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.

  2. On the Table Designer menu, click Indexes/Keys.

  3. In the Indexes/Keys dialog box, click Add.

  4. In the grid under General, click Type and choose Unique Key from the drop-down list box to the right of the property.

  5. On the File menu, click Savetable name.

Using Transact-SQL

To create a unique constraint

  1. In Object Explorer, connect to an instance of Database Engine.

  2. On the Standard bar, click New Query.

  3. Copy and paste the following example into the query window and click Execute. The example creates the table TransactionHistoryArchive4 and creates a unique constraint on the column TransactionID.

    USE AdventureWorks2012;  
    GO  
    CREATE TABLE Production.TransactionHistoryArchive4  
     (  
       TransactionID int NOT NULL,   
       CONSTRAINT AK_TransactionID UNIQUE(TransactionID)   
    );   
    GO  
    
    

To create a unique constraint on an existing table

  1. In Object Explorer, connect to an instance of Database Engine.

  2. On the Standard bar, click New Query.

  3. Copy and paste the following example into the query window and click Execute. The example creates a unique constraint on the columns PasswordHash and PasswordSalt in the table Person.Password.

    USE AdventureWorks2012;   
    GO  
    ALTER TABLE Person.Password   
    ADD CONSTRAINT AK_Password UNIQUE (PasswordHash, PasswordSalt);   
    GO  
    
    

To create a unique constraint in an new table

  1. In Object Explorer, connect to an instance of Database Engine.

  2. On the Standard bar, click New Query.

  3. Copy and paste the following example into the query window and click Execute. The example creates a table and defines a unique constraint on the column TransactionID.

    USE AdventureWorks2012;  
    GO  
    CREATE TABLE Production.TransactionHistoryArchive2  
    (  
       TransactionID int NOT NULL,  
       CONSTRAINT AK_TransactionID UNIQUE(TransactionID)  
    );  
    GO  
    
    

    For more information, see ALTER TABLE (Transact-SQL), CREATE TABLE (Transact-SQL), and table_constraint (Transact-SQL).