6

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

8

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

enter image description here

4
  • Thank you ! It works like a charm.
    – Jérémie
    Commented 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
    Commented 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 right
    – Babel
    Commented Dec 1, 2022 at 5:53
  • great! is there a way to enforce the not null constraint when field A is 'foo'? Commented Jan 9 at 19:23
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.