Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give a unique constraint to a combination of columns in Oracle?

I have a Table with 4 Columns

Each Column will be A,B,C,D

Column A is the Primary key. Column B has unique name constraint.

Now I want to remove the unique constraint for column B and give a unique constraint by combining the columns B, C and D. So the table will allow only one row with a particular value in columns B,C and D.

How can I give this type of a constraint?

I tried giving the composite unique key like :

ALTER TABLE TABLENAME ADD CONSTRAINT CONSTRAINT_NAME UNIQUE (COLUMN_B, COLUMN_C, COLUMN_D) 

But it is checking whether any one of the constraint is present rather than checking for the combination of unique key constraint.

like image 952
Nigel Thomas Avatar asked Jun 27 '13 12:06

Nigel Thomas


People also ask

How do I create a unique constraint in multiple columns?

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 Key Be combination of columns?

You cannot designate the same column or combination of columns as both a primary key and a unique key or as both a primary key and a cluster key.

Can Unique Key have multiple columns?

UNIQUE constraint ensures that all values in a specific column is different. UNIQUE key does not allow duplicate values. UNIQUE key allows NULL values but does not allow NULL values multiple times. We can create multiple UNIQUE columns on one table however only one PRIMARY KEY for table.

How do I create a composite unique key in Oracle?

ALTER TABLE table_name DROP CONSTRAINT myUniqueConstraint; Now, you can create a UNIQUE Constraint by using the keyword UNIQUE with the combination of required Columns. For Example: ALTER TABLE table_name ADD CONSTRAINT myUniqueConstraint UNIQUE(B, C, D);


1 Answers

Create a unique key on those columns

ALTER TABLE YourTable   add CONSTRAINT YourTable_unique UNIQUE (B, C, D); 

Oracle/PLSQL: Unique Constraints

like image 102
saamorim Avatar answered Oct 04 '22 14:10

saamorim