Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check constraint with condition

I'm wondering if this condition can be done by a check constraint or do I need to create a trigger.

Condition : if student admited date is not null then exam mark is null

Remark: Constaint case OR Trigger

What I tried :

ALTER TABLE ADMITED_TABLE
ADD CONSTRAINT AAAA CHECK
 ( CASE  WHEN  DATEADMITED IS NOT NULL THEN MARK NULL END);

Error:

ORA-00920: invalid relational operator
00920. 00000 -  "invalid relational operator"
like image 811
David Edgar Avatar asked May 04 '26 01:05

David Edgar


2 Answers

A check constraints takes a boolean condition, so you'd have to frame this logic in a form of such a condition:

ALTER TABLE ADMITED_TABLE
ADD CONSTRAINT AAAA CHECK
(dateadmited IS NULL OR mark IS NULL);
like image 199
Mureinik Avatar answered May 06 '26 19:05

Mureinik


I must be misreading David's requirement, because my solution is:

ALTER TABLE admitted_table
    ADD CONSTRAINT aaaa CHECK
            ( (dateadmitted IS NOT NULL
           AND mark IS NULL)
          OR dateadmitted IS NULL);

The following are my test cases:

-- Succeeds
INSERT INTO admitted_table (
           dateadmitted, mark
            )
     VALUES (SYSDATE, NULL);

-- Fails due to check constraint
INSERT INTO admitted_table (
           dateadmitted, mark
            )
     VALUES (SYSDATE, 10);

-- Succeeds
INSERT INTO admitted_table (
           dateadmitted, mark
            )
     VALUES (NULL, 99);
like image 29
Brian Leach Avatar answered May 06 '26 19:05

Brian Leach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!