SQL Unique Key Constraint

SQL Unique Constraint will ensure that no duplicate values are inserted into the table columns. For example, if we want to ensure that the Employee or a customer has to log in using a single email address. Then we can assign a Unique Constraint to that column.

It will accept a single null value. We can create a SQL Server Unique Constraint using the Transact query and the Management Studio.

Create SQL Unique Key Constraint using Management Studio

Please go to the Object Explorer to create a Unique Constraint using the SQL Management Studio. Right-click on the table on which you want to create (here it is CustomerRecords) and select the Design option

Open Table in Design Mode 1

Once you click the Design option, the CustomerRecords table will open in design mode. As you can see, the table has 7 columns of different data types, and our task is to add the Unique Constraint to the Email Address column.

To create a SQL Unique constraint, right-click on the Column name, and select the Indexes/Keys.. option.

choose Indexes or Keys Option from Context menu 3

Once you select the SQL Server Indexes/Keys.. option, a new window will open. To create a new key, Please click on the Add button.

Click on the Add Button to Add New index or key 4

Once you click the Add button, it will create an index with a default name. Next, please navigate to the General Section to select the column you want to apply.

SQL Unique Key Constraint 5

Here we want to use the SQL Unique Key constraint on the Email Address column, and that’s why we are selecting the same.

Specify the index Column Name and Sort Order 6

Next, Please change the Type from default Index to Unique Key.

Set Type as SQL Unique Key Constraint 7

Lastly, if you want to change the identity name, use the Name property to change. Once complete, click the close button, which will create a SQL Unique Key constraint on the Customer records table for you.

Assign a Name to it 8

Let’s see the internal code generated by the Management Studio by right-clicking on the table -> script as – > create to new query window option.

SQL Unique Constraint Code 9

Create SQL Unique Constraint using a query

How to create a unique key in the SQL server using the Transact statement? We have multiple options to create this using query. If you don’t want to assign any specific name to the key, use the following option. Please refer to the Create Table article.

CREATE TABLE [dbo].[CustomerRecords](
	[CustKey] [int] NOT NULL UNIQUE,
	[FirstName] [varchar](50) NOT NULL,
	[LastName] [varchar](50) NULL,
	[BirthDate] [date] NULL,
	[EmailAddress] [nvarchar](50) NULL,
	[Yearly Income] [money] NULL,
	[Profession] [nvarchar](100) NULL
)
GO
Messages
-------
Command(s) completed successfully.

Create a Unique Key with a Meaningful Name

It allows you to assign a meaningful name.

CREATE TABLE [dbo].[CustomerRecords](
	[CustKey] [int] NOT NULL,
	[FirstName] [varchar](50) NOT NULL,
	[LastName] [varchar](50) NULL,
	[BirthDate] [date] NULL,
	[EmailAddress] [nvarchar](50) NULL,
	[Yearly Income] [money] NULL,
	[Profession] [nvarchar](100) NULL,
	CONSTRAINT UC_CustomerRecords_CustKey UNIQUE (CustKey)
)
GO

We just added it to the CustKey column.

Messages
-------
Command(s) completed successfully.

Insert records into the Table with SQL Unique Key Constraint

Let me insert a value into the table using the INSERT Statement.

-- Inserting Values
INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [BirthDate], [EmailAddress], [Yearly Income], [Profession])
     VALUES
           (1, 'Tutorial', 'Gateway', '10-04-1995', 'ab@abd.com', 92500, 'Admin'),
	   (2, 'Steve', 'Lara', '10-04-1989', 'abcd@abcd.com', 19500, 'Software Developer'),
	   (3, 'Jack', 'Smith', '10-08-1985', 'xyz@abcd.com', 25000, 'Manager' ),
	   (4, 'Ramesh', 'Kumar', '10-05-1983', 'mnopq@abcs.com', 75000, 'Sales Manager')
GO
Messages
-------
(4 row(s) affected)

See the data that we inserted.

See the distinct Records in Table  13

Error: Add Duplicate records to Unique Key

Let me add the Duplicate value to the key column ( CustKey)

INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [BirthDate], [EmailAddress], [Yearly Income], [Profession])
     VALUES
       (1, 'Gateway', 'Tutorial', '10-04-1995', 'abcdefg@tutorialgateway.org', 92500, 'Admin')
GO

It is throwing an error.

Error Message 2627. 14

SQL Server Unique Constraint on Existing table

To add a unique constraint to the existing table, we use the Alter Table Statement to alter the table content. Then used the ADD UNIQUE statement to add this constraint.

ALTER TABLE[CustomerRecords]
ADD UNIQUE([EmailAddress])

OR, use the following unique constraint approach to add the Meaningful name.

ALTER TABLE[CustomerRecords]
ADD CONSTRAINT UC_CustomerRecords_EmailAddress UNIQUE([EmailAddress])

Let’s see the internal code generated by it by right-clicking on the table -> script as – > create to new query window option.

SSMS Auto generated code 15

Insert NULLS into the SQL Unique Key Constraint table column

Let us see what will happen when we insert the NULL values into the SQL Unique key column.

-- Inserting Values
INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [BirthDate],  [Yearly Income], [Profession])
     VALUES
       (5, 'Gateway', 'Tutorial', '10-04-1995', 92500, 'Admin')
GO
Insert Null Values 16

Let me insert one more NULL value into the Email Address Column, which has a constraint.

INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [BirthDate],  [Yearly Income], [Profession])
     VALUES
       (6, 'TutorialGateway', 'Website', '12-05-1995', 92500, 'Admin')
GO

It is throwing an error because it will accept only one NULL value.

Error Message 2627. Cannot insert duplicates 17

Drop SQL Unique Constraint using Management Studio

Right-click on the table name, and click the Design option. Next, select the Indexes/Keys..option, select the constraint you want to delete, and click the Delete button.

DROP SQL Unique Constraint 18

Delete SQL Unique Constraint using Drop constraint

If you know the name, use the DROP Constraint and the ALTER TABLE Statements.

ALTER TABLE [dbo].[CustomerRecords]   
DROP CONSTRAINT UC_CustomerRecords_CustKey;  
GO

If you don’t know the name, use the below SELECT Statement to get the Constraint name.

-- To find the Name
SELECT name  
FROM sys.key_constraints
WHERE OBJECT_NAME(parent_object_id) = N'CustomerRecords';  
GO  
-- Delete or Drop
ALTER TABLE [CustomerRecords]   
DROP CONSTRAINT UC_CustomerRecords_CustKey;  
GO
Finding existing name 19

Then you can use the ALTER TABLE Statement to Drop the constraint.

SQL ALTER TABLE DROP Unique Constraint 20

How to add a Unique Key on Multiple Columns?

You can use this query to add the Unique key on Multiple Columns.

CREATE TABLE [dbo].[CustomerRecords](
	[CustKey] [int] NOT NULL,
	[FirstName] [varchar](50) NOT NULL,
	[LastName] [varchar](50) NULL,
	[BirthDate] [date] NULL,
	[EmailAddress] [nvarchar](50) NULL,
	[Yearly Income] [money] NULL,
	[Profession] [nvarchar](100) NULL,
	CONSTRAINT UC_CustomerRecords_CustKeyEmailID UNIQUE (CustKey, EmailAddress)
)
GO
Categories SQL