Sample Header Ad - 728x90

NOT NULL if value is true in another column

22 votes
1 answer
26198 views
I have a similar table to this one create table my_table ( id serial, attribute boolean, number integer ) Is there a way to have it force not null in column number IF attribute value is true? So if a record is saved with attribute value 'true' then number must be given a value. EDIT: After some digging I have tried this alter table my_table add constraint number_must_have_value CHECK (attribute = 't' and number IS NOT NULL) It throw constraint is violated by some row, but if I run: select * from my_table where attribute = 't' and number IS NOT NULL I retrive 0 rows. So my data seem to be OK? To force it anyway I try to use constraint number_must_have_value NOT VALID CHECK (attribute = 't' and number IS NOT NULL) But can't get the NOT VALID option to work. I get a syntax error. Is it not in the right place?
Asked by geogrow (384 rep)
Aug 1, 2016, 10:14 AM
Last activity: Dec 10, 2024, 02:21 PM