SQL Unique Constraint

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

Create SQL Unique Constraint

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

Creating SQL Unique key using SSMS

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

SQL Unique Constraint 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.

SQL Unique Constraint 3

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

SQL Unique Constraint 4

Once you click on the Add button, SQL will create an index with a default name. Please navigate to the General Section to select the column on which you want to apply the Unique Constraint

SQL Unique Constraint 5

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

SQL Unique Constraint 6

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

SQL Unique Constraint 7

Lastly, if you want to change the Constraint name, use the Name property to change. Once you were complete, click the close button, and that will create a Unique Key on Customer records table for you.

SQL Unique Constraint 8

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

SQL Unique Constraint 9

Create SQL Unique Constraint using T-SQL

How to create a unique key in the SQL server using the Transact SQL statement. We have multiple options to create a unique key in SQL server using query. If you don’t want to assign any specific name to the key, use the following option. Refer to 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

Output

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

It allows you to assign meaningful name to the SQL Unique key

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 the unique constraint to the CustKey column.

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

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

-- Inserting Values into SQL Server UNIQUE Constraint
INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [BirthDate], [EmailAddress], [Yearly Income], [Profession])
     VALUES
           (1, 'Tutorial', 'Gateway', '10-04-1995', '[email protected]', 92500, 'Admin'),
	   (2, 'Steve', 'Lara', '10-04-1989', '[email protected]', 19500, 'Software Developer'),
	   (3, 'Jack', 'Smith', '10-08-1985', '[email protected]', 25000, 'Manager' ),
	   (4, 'Ramesh', 'Kumar', '10-05-1983', '[email protected]', 75000, 'Sales Manager')
GO

Output

Messages
-------
(4 row(s) affected)

See the data that we inserted

SQL Unique Constraint 13

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

-- Inserting Values into SQL Server UNIQUE Constraint
INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [BirthDate], [EmailAddress], [Yearly Income], [Profession])
     VALUES
       (1, 'Gateway', 'Tutorial', '10-04-1995', '[email protected]', 92500, 'Admin')
GO

It is throwing an error.

SQL Unique Constraint 14

SQL Unique Constraint on Existing table

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

-- Creating SQL Server UNIQUE Constraint
ALTER TABLE[CustomerRecords]
ADD UNIQUE([EmailAddress])

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

-- Creating SQL Server UNIQUE Constraint
ALTER TABLE[CustomerRecords]
ADD CONSTRAINT UC_CustomerRecords_EmailAddress UNIQUE([EmailAddress])

Let see the internal code generated by the SQL, by right-clicking on the table -> script as – > create to new query window option

SQL Unique Constraint 15

Insert NULLS in SQL Unique Key

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

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

Let me insert one more NULL value into the Email Address Column.

-- Inserting Values into SQL Server UNIQUE 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 Sql Server Unique key will accept only one NULL value

SQL Unique Constraint 17

Drop SQL Unique Constraint using SSMS

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

SQL Unique Constraint 18

Delete SQL Unique Constraint using Drop constraint

If you know the SQL Unique constraint name, use the DROP Constraint statement along with the ALTER TABLE Statement

-- Deleting SQL Server UNIQUE Constraint
ALTER TABLE [dbo].[CustomerRecords]   
DROP CONSTRAINT UC_CustomerRecords_CustKey;  
GO

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

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

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

SQL Unique Constraint 20

Inserting SQL Unique Constraint on Multiple Columns

You can use this query to add SQL 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