My question is about checking constraint, the normal syntax is :
ALTER TABLE barracks
ADD CONSTRAINT chk_barracks CHECK( status IN('Destroyed', 'constructed'))
This means that column status should be destroyed OR constructed.
In the following I am specifying that barracks doesn't accept null values
ALTER TABLE barracks
ADD CONSTRAINT chk_barracks CHECK(status IN('Destroyed', 'constructed')
AND status IS NOT NULL)
Now I added column colour. I want to specify if barracks is constructed, then colour should be RED only and the column STATUS should be NOT NULL
If BARRACKS IS DESTROYED
Then colour should be BLACK and the column STATUS should be NULL.
So here is the checking constraint that I wrote:
ALTER TABLE barracks
ADD CONSTRAINT chk_barracks CHECK( ((status IN ('Destroyed', 'constructed')
AND status IS NOT NULL)
AND (color IN('RED') ))
OR (( status IN('Destroyed', 'constructed')
AND status IS NULL)
AND (color IN('BLACK') )))
The problem that if color is RED, I am still able to insert NULL into the column status. How to solve this constraint in a way it will check my conditions that I have mentioned above?