Quantcast
Channel: Journey to SQL Authority with Pinal Dave » SQL Constraint and Keys
Viewing all articles
Browse latest Browse all 32

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

$
0
0

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)


Filed under: PostADay, SQL, SQL Authority, SQL Constraint and Keys, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

Viewing all articles
Browse latest Browse all 32