how to modify an existing check constraint?

231.8k views Asked by At

Is there any way to modify an existing check constraint on a table other than dropping and re-creating it?

create table t ( n number);
ora10g> Tabelle wurde erstellt.

ora10g> alter table t add constraint ck check(n>0);

Tabelle wurde geõndert.

ora10g> alter table t modify constraint ck check(n<0);
alter table t modify constraint ck check(n<0)
                                   *
FEHLER in Zeile 1:
ORA-00933: SQL-Befehl wurde nicht korrekt beendet
5

There are 5 answers

2
Adam Musch On BEST ANSWER

You have to drop it and recreate it, but you don't have to incur the cost of revalidating the data if you don't want to.

alter table t drop constraint ck ;
alter table t add constraint ck check (n < 0) enable novalidate;

The enable novalidate clause will force inserts or updates to have the constraint enforced, but won't force a full table scan against the table to verify all rows comply.

2
Jon Heller On

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

0
Oleg Danu On

NO, you can't do it other way than so.

0
sunleo On
create table Gender_Long(id integer,gender varchar2(10), constraint Gender_Long_pk primary key(id));
create table Employee(id integer,name varchar2(10),gender integer, constraint Employee_pk primary key(id),
    constraint Employee_fk foreign key(gender) references Gender_Long(id));

insert into Gender_Long values(1,'male');
insert into Gender_Long values(2,'female');

insert into Employee values(1,'Raj',1);
insert into Employee values(2,'Maha',1);
insert into Employee values(3,'Devi',2);

create table Gender_Short(id integer,gender varchar2(10), constraint Gender_Short_pk primary key(id));

insert into Gender_Short values(1,'M');
insert into Gender_Short values(2,'F');

ALTER TABLE Employee add constraint Employee_fk2 foreign key(gender) references Gender_Short(id);

ALTER TABLE Employee DROP CONSTRAINT Employee_fk;

drop table Gender_Long;
4
Witold Kaczurba On

Create a new constraint first and then drop the old one.
That way you ensure that:

  • constraints are always in place
  • existing rows do not violate new constraints
  • no illegal INSERT/UPDATEs are attempted after you drop a constraint and before a new one is applied.