39

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.

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
Nigel Thomas
  • 1,881
  • 8
  • 30
  • 50
  • @Naveen I gave the constraint as you told.. but it seems that the constraint only checks for any one of the column names... I want it to be like a new row will not be allowed to enter all the three column values are already existing in the table. – Nigel Thomas Jun 28 '13 at 06:55
  • 1
    hai @nigelthomas view this link http://stackoverflow.com/questions/1109614/how-can-i-create-a-sql-unique-constraint-based-on-2-columns – Naveen Kumar Alone Jun 28 '13 at 07:05

3 Answers3

65

Create a unique key on those columns

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

Oracle/PLSQL: Unique Constraints

Glenn
  • 8,932
  • 2
  • 41
  • 54
saamorim
  • 3,855
  • 17
  • 22
9

First of all you should drop an existing Constraint by using below ALTER Query.

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);

Detailed explanation of UNIQUE Constraint here.

Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
2

ALTER TABLE table_name DROP CONSTRAINT constraint_name;

CREATE UNIQUE INDEX constraint_name ON table_name (B,C,D)

Sunil Kumar
  • 5,477
  • 4
  • 31
  • 38