Create Unique Constraints
You can create a unique constraint in SQL Server 2012 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:
-
To create a unique constraint, using:
To create a unique constraint
-
In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.
-
On the Table Designer menu, click Indexes/Keys.
-
In the Indexes/Keys dialog box, click Add.
-
In the grid under General, click Type and choose Unique Key from the drop-down list box to the right of the property.
-
On the File menu, click Save table name.
To create a unique constraint
-
In Object Explorer, connect to an instance of Database Engine.
-
On the Standard bar, click New Query.
-
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
-
In Object Explorer, connect to an instance of Database Engine.
-
On the Standard bar, click New Query.
-
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
-
In Object Explorer, connect to an instance of Database Engine.
-
On the Standard bar, click New Query.
-
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).