Is there a way to use if logic in an oracle sql check constraints?
This is my pseudo table:
create table child
(
name,
behaviour,
treat,
);
Now what i want is that if the behaviour
of child = 'bad'
then treat != 'lollies'
.
Sometimes it is easier to express using NOT to define what is not allowed:
CHECK (NOT (behaviour = 'bad' AND treat = 'lollies'))
... which means same as:
CHECK (behaviour != 'bad' OR treat != 'lollies')
It is easy to get this wrong, as other answers have shown!
ALTER TABLE child
ADD CONSTRAINT bad_behaviour_CK
CHECK (NOT (behaviour = 'bad' AND treat = 'lollies')) ;
Tesed in SQL-Fiddle
If you have learned propositional logic before, we can apply it in this situation and explain how the top voted answer is derived.
We let A be the proposition of behavior = 'bad'
and B be the proposition of treat != 'lollies'
. The statement of "If behavior = 'bad'
, then treat != 'lollies'
" can be written as " A → B ".
Note that " A → B " is logically equivalent to "¬ A ∨ B " (¬ means NOT and ∨ means OR). Therefore, we can translate the statement "¬ A ∨ B " back to " behavior != 'bad'
OR 'treat != 'lollies'
".
In terms of SQL, we can write this as:
CHECK (behaviour <> 'bad' OR treat <> 'lollies')
This is equivalent to:
CHECK (NOT (behaviour = 'bad' AND treat = 'lollies'))
Try this
create table children (
childname VARCHAR2(50), behaviour VARCHAR2(50),treats VARCHAR2(50),
constraint behave_treat check (behaviour = 'bad' AND treats != 'lollies')
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.