Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs
    • SQL FAQ’s

SQL Unique Constraint

by suresh

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.

TIP: Unique Constraint in SQL Server will accept a single null value.

Create SQL Unique Constraint

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.

SQL Unique Constraint 2

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 me show you 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.

Here 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 that you want to create, then you can 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

SQL Unique Constraint 10

The following method 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.

OUTPUT

SQL Unique Constraint 11

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

SQL Unique Constraint 12

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

OUTPUT

SQL Unique Constraint 14

As you can see from the above screenshot, it is throwing an error.

SQL Unique Constraint on Existing table

To add SQL Server unique constraint on the existing table, we are using 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

OUTPUT

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

OUTPUT

SQL Unique Constraint 17

As you can see from the above screenshot, it is throwing an error. Because Sql Server Unique key will accept only one NULL value

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 that you want to delete, 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

OUTPUT

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

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy