Skip to Main Content
  • Questions
  • Adding a check constraint to existing table to avoid both columns to be null and allow all other 3 combinations

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, raj.

Asked: January 09, 2019 - 5:46 pm UTC

Last updated: January 10, 2019 - 7:12 am UTC

Version: oracle 12 standard

Viewed 1000+ times

You Asked

I have a requirement that has below output:


Col1 col2
NOTNULL NOTNULL(my table already has this data and I want to keep it)
NULL NOTNULL(my table already has this data and I want to keep it)
NOTNULL NULL (my table already has this data and I want to keep it)
NULL NULL (my table already has this data and wanted to delete this data and add a constraint to the table where it will allow first 3 combinations of data and the data with both columns col1 and col2 is null should not be allowed.


I need a check constraint(that allows only first 3 combinations) query to alter the table


Any help will be highly appreciated.

Thanks.

with LiveSQL Test Case:

and Connor said...

Here you go

SQL> create table t ( c1 int, c2 int );

Table created.

SQL> insert into t values (1,1);

1 row created.

SQL> insert into t values (1,null);

1 row created.

SQL> insert into t values (null,1);

1 row created.

SQL> insert into t values (null,null);

1 row created.

SQL>
SQL> alter table t
  2  add constraint CHK check ( not ( c1 is null and c2 is null ) )
  3  enable novalidate;

Table altered.

SQL>
SQL> delete from t where c1 is null and c2 is null;

1 row deleted.

SQL>
SQL> alter table t
  2  modify constraint CHK
  3  enable validate;

Table altered.

SQL>
SQL> insert into t values (null,null);
insert into t values (null,null)
*
ERROR at line 1:
ORA-02290: check constraint (MCDONAC.CHK) violated



Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Design

New to good database design? Check out Chris Saxon's full fundamentals class.