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.

Babel
79.7k15 gold badges96 silver badges244 bronze badges
asked Jan 6, 2022 at 16:32

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

answered Jan 6, 2022 at 17:04
4
  • Thank you ! It works like a charm. 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... 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 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, 2024 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)
answered May 11, 2023 at 22:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.