SQL Unique Constraint

SQL Unique Constraint will ensure that no duplicate values inserted into the 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

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

To create a SQL Unique Constraint using the Management Studio, Please go to the Object Explorer. 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 on the Add button, it will create an index with a default name. Please navigate to the General Section to select the column on which you want to apply.

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.

Specify the index Column Name and Sort Order 6

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

SQL Unique Constraint 7

Lastly, if you want to change the identity 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 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 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.

It allows you to assign 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.

Let me insert 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 Unique Records in Table  13

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.

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 this constraint.

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

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

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

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

SQL Unique Constraint 15

Insert NULLS

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

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 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

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

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

SQL Unique Constraint 20

Inserting 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