I’m trying to create a check on a few columns in my database that forces them to be null unless the value of another column is yes. I’ve tried something like
ALTER TABLE TABLE1
ALTER Column1
CHECK (Column2 = 'y')
But that doesn’t seem to be working. Is there a way to do it like this, or is there a better way around this problem? Any help in the right direction would be great.
If you want to require that
col1is null unlesscol2is ‘y’, you can write your CHECK constraint as:If you additionally want to require that
col1must have a value whencol2is ‘y’, you can write the constraint as:You should write this as a table constraint, btw. I don’t think a column constraint is allowed to refer to other columns. (But a column constraint is just another way of writing a table constraint anyway, so you don’t lose anything by writing table constraints instead.)