Updating field values if condition met, but leave the original values if condition not met in QGIS

distanceexpressionfield-calculatorpoint-in-polygonqgis

I'm sure this is probably quite simple but I'm still learning the syntax for field calc expressions. I have a points layer with the field "Distance" that I want to update using my expression:

if(
    distance(
        $geometry,
        geometry(
            get_feature('Site Boundary', 'id', '1')
            )
        ) = 0,
    '0',
    '1'
    )

In simple words: If(distance between current point feature and 'Site Boundary' polygon = 0, then write '0', else write '1'.

If a point is within the polygon 'Site Boundary', the distance function returns '0'. What is great, but my expression then overwrites all other values with '1'. How can I alter the expression to leave the original distance values if the condition is not met?

Best Answer

In the if-condition, change the result_when_false argument from 1 to the name of the field you are changing ("your_fieldname" in the following example): then the value of this field will be copied:

if(
    distance(
        $geometry,
        geometry(
            get_feature('Site Boundary', 'id', '1')
            )
        ) = 0,
    '0',
    "your_fieldname"
    )

By the way: setting zero in single quotes '0' results in an output formatted as a string (text). If you want a number (integer), simply write it without quotes: 0. Or use a case when ... then ... end statment without else-part if you want to get no output in all other cases (see documentation).

Related Question