Using the field calculator, I'm trying to update an attribute only if it equals to zero:

CASE WHEN  "Z" = 0
"Z" =  rand(1,100)

This let the 0 values as they are and updates all others to "NULL".

This IF statement doesn't work either:

IF( "Z" = 0,
"Z" = rand(1,100),
"Z" = "Z"

It sets all values greater than zero to 1 and let the others = 0.

What's wrong with these statements?
Z is a double.
I clicked all functions and element in the search list so there shouldn't be any typo.

And what kind of language is this, I can't recognize SQL; it seems to be some kind of "internal to QGIS language".

1 Answer 1


The value that is written into the attribute table depends on what field calculator returns. In your case:

CASE WHEN  "Z" = 0
THEN "Z" = rand(1,100)

means that it compares Z and 0, and if that's true, it compares Z and a random value from 1 to 100, which has to be false because Z is 0. That's why it writes 0 (=False) into the fields which were 0. And the expression doesn't return anything for all other input values. That's why it writes NULL everywhere else.

This means, that you have to change the expression as follows:

CASE WHEN  "Z" = 0
THEN rand(1,100)

Afaik, this is in line with SQL as interpreted by Postgres, which also supports this kind of CASE statements.

The IF statements were introduced because users wanted something more Excel-like. Your example is failing for the same reason stated above.

  • Ok thanks, so I did that :<br/><br/> IF( "Z" = 0, <br/> rand(1,100),<br/> "Z"<br/> )<br/> and QGIS turns grey for about one hour now... <br/> Did I fall in some kind of infinite loop ? CPU usage is 100%. <br/>I only have 20 points in an empty test layer. Commented Jul 23, 2016 at 12:01
  • Sorry, I cannot reproduce this issue.
    – underdark
    Commented Jul 23, 2016 at 13:15

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.