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 CREATE TABLE [dbo].[Customer]( [FirstName] [varchar](50) NULL, [LastName] [varchar](50) NULL, [SSN] VARCHAR(11) )
Create Unique Constraint on SSN Column by using below script.
Alter Table dbo.Customer
Add Constraint 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.
Alter Table dbo.Customer
Add Constraint 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 |
Video Demo : How to create Unique Constraint on Column for already existing Table
No comments:
Post a Comment