Scenario:
You are working as SQL Server developer, you need to create Unique Constraint on already existing table called dbo.Customer on column SSN.
Solution:
Let's create the dbo.Customer table first by using below script.
USE [YourDatabaseName]
GO
CREATETABLE [dbo].[Customer](
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[SSN] VARCHAR(11)
)
Create Unique Constraint on SSN Column by using below script.
AlterTable dbo.Customer
AddConstraint UQ_dbo_Customer_SSN Unique(SSN)
If you need to create Unique Constraint on multiple columns, you can use below syntax. I am creating Unique Constraint for FirstName and LastName.
AlterTable dbo.Customer
AddConstraint UQ_dbo_Customer_FName_LName Unique(FirstName,LastName)
Use below query to check if Unique Constraints are created successfully.
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'UNIQUE'
How to create Unique Constraint on Column for existing SQL Server Table |