Does anyone know it is possible in QGIS to add a constraint to a field not to be null, only when another field has a certain value.
For example I have a field A that can be with value 'foo' or 'bar' and a field B with free text. I want the field B to be not null (mandatory to fill), when field A is 'foo'. But it can be empty when field A is 'bar'.
Hope I'm clear enough in my description.
2 Answers 2
On field B, for constraints use this expression:
case
when "field_A" = 'foo' then not (field_B is NULL)
when "field_A" <> 'foo' then field_B is NULL or field_B is not NULL
end
-
Thank you ! It works like a charm.Jérémie– Jérémie2022年01月07日 08:20:57 +00:00Commented Jan 7, 2022 at 8:20
-
@Babel shouldn't field_B be surrounded by double quotes ("field_B") in your answer? I thought that fields always needed the double quotes...Stu Smith– Stu Smith2022年12月01日 00:46:39 +00:00Commented Dec 1, 2022 at 0:46
-
It's not mandatory, fields can also be written without quotes. But probably it's better to use quotes, you're rightBabel– Babel2022年12月01日 05:53:24 +00:00Commented Dec 1, 2022 at 5:53
-
great! is there a way to enforce the not null constraint when field A is 'foo'?Eric Walter– Eric Walter2024年01月09日 19:23:11 +00:00Commented Jan 9, 2024 at 19:23
Is imply wanted to point out that this could also be achieved with a if() statement:
if("field_A" = 'foo',"field_B" IS NOT NULL,"field_B" IS NULL OR "field_B" IS NOT NULL)
Explore related questions
See similar questions with these tags.