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

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 (http://blog.sqlauthority.com)

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s