Skip to Main Content
  • Questions
  • Check constraints on more than one column in a table

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, mfz.

Asked: March 10, 2011 - 11:48 am UTC

Last updated: March 10, 2011 - 1:33 pm UTC

Version: 11.2.0.2

Viewed 1000+ times

You Asked

Tom , 

Is it possible to have a check constraint on more than one column . 
In the example below , I would like to have a constraint , if the rflag is 'Y' then rdate should be not null. 
How can this be accompolished ?

I dont want employ trigger unless otherwise , if that is only option . 



create table t_cons 
( rkey int primary key, 
  rflag char(1)  , 
  rdate date  default sysdate ) 
  
alter table t_cons add constraint cons_rflag check ( rflag  in ('Y', 'N')  ) ;

alter table t_cons add constraint cons_rdate check ( rfllag = 'Y' and rdate is not null ) ;

and Tom said...

the short answer is "yes"

if the rflag is 'Y'
then rdate should be not null.


that would be expressed as:

check ( rflag <> 'Y' or rdate is not null );



If the rflag is not Y, rdate can be anything - and the constraint is happy.

If the rflag is Y, rdate then must be not null for the constraint to be happy.


Rating

  (1 rating)

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

Comments

mfz, March 10, 2011 - 1:49 pm UTC

Thank you .

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library