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 (https://blog.sqlauthority.com)
4 Comments. Leave new
Speaking of unique constraints, I am adding a GUID column to some tables, but do not want to replicate that column. I have tried adding that constraint, but it does not seem to like it. Any idea
sir i want to remove unique in the table
how you can delete a unique constraint on the table
Thanks ,
Very helpful