Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 Unique constraint on two columns

How do you add a unique constraint in SQL Server 2005 to two columns? So lets say that I have:

PK, A, B ... x1  1  1 x2  1  2 x3  2  1 x4  2  2 

I should not be able to add another row 'x5' and have the values for A and B be 1,1 as they are already in the database in x1?

Ok we managed to get it to work and thanks to OMG. Go to the table view, select the two columns, right click and select 'indexes/keys' - general tab, select the columns you want to be unique and then set 'is unique' to true. This is using the table designer.

Thanks.

like image 938
flavour404 Avatar asked Feb 01 '10 23:02

flavour404


People also ask

How do I add a unique constraint in two columns in SQL?

SQL UNIQUE constraint for 2 columns example Notice that we named the UNIQUE constraints using CONSTRAINT keyword. We can use this name to remove the UNIQUE constraint later if we want. To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.

Can we apply unique constraint on multiple columns?

Introduction to SQLite UNIQUE constraint To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns.

Can unique constraints be multiple?

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

How do I find unique two column combinations in SQL?

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.


1 Answers

ALTER TABLE YourTable ADD CONSTRAINT UQ_YourTable_ConstraintName UNIQUE(A, B) 
like image 167
AdaTheDev Avatar answered Oct 14 '22 05:10

AdaTheDev