SQL SERVER – Create Unique Constraint on Table Column on Existing Table

Here is the question I received on twitter.

“Can we create a unique constraint on table column on Existing Table?”

SQL SERVER - Create Unique Constraint on Table Column on Existing Table constraintimage

Of course Yes!

Here is how you can create a unique constraint on the table which already exist in our system.

USE tempdb
GO
-- Create Table
CREATE TABLE Table1 (ID INT, Col1 VARCHAR(100))
GO
-- Alter Table Create Constraint
ALTER TABLE Table1
ADD CONSTRAINT UX_Constraint UNIQUE (Col1)
GO
-- Clean up
DROP TABLE Table1
GO

If your table already exists you can use above method to create the constraint. However, if you are about to create tables, you can just specify UNIQUE in the schema definition of Create Table itself. We will discuss about this in a future post.

Reference: Pinal Dave (https://blog.sqlauthority.com)

Previous Post
MySQL – Learn MySQL Online – 8 MySQL Courses at Pluralsight
Next Post
MySQL – Change the Limit of Row Retrieved in MySQL Workbench

Related Posts

4 Comments. Leave new

Leave a Reply

Menu