Is it possible to use a local variable in a label expression/field calculator in QGIS 3? I have an extremely long CASE expression that generates a String for the labels of my objects, and I would like to process the string after I have generated it. To do this, however, I would need to save the string in a local variable and refer to the variable in the processing afterwards.

Here's a shortened version of my problem:

CASE when ("A" != 'null'  then 'A: ' ||  "A" || ', ' else '' end ||
CASE when ("B" != 'null' then 'B: ' ||  "B" || ', ' else '' end ||
CASE when ("C" != 'null' then 'C: ' ||  "C" || ', ' else '' end

This creates something like: "A: 3, B: 1, "

There's ", " always after the last variable and I would like to remove that from the end. The expression I'm using is so long that it exceeds the character limit of the field calculator. That's why I would like to save the string in a local variable "input", then use left(input, length(input) - 2). This would delete the last two ", " and make the string "A: 3, B: 1". It will have to be done like this because the table will be updated in the future.

Is this possible?

  • 1
    Why not reword your expression so that the comma only appears with the second CASE statement? so when "A" != null then 'A: ' || "A"; case when B != null then ', B: ' || "B" .. .and so on
    – she_weeds
    Commented Aug 13, 2018 at 1:29
  • 1
    @she_weeds if "A" is null, then there'd be a comma at the beginning...@nintskari, did you try the Expression Dialog?
    – geozelot
    Commented Aug 15, 2018 at 7:55

1 Answer 1


If you use the Expression Dialog in the Labels tab of the layer properties, you can add CASE expressions till the end of days...

Use double spaces following each string, trim() the trailing and replace() the others with ,:

      CASE WHEN "A" != 'null' THEN 'A: ' || "A" || '  ' ELSE NULL END,
  '  ',
  ', '
  • Thank you! That actually does work! But I used a different workaround. I made it so that the ", " is at the beginning, then used trim(). Apparently, the length of trim() function doesn't have to be precise, so I could just use it to trim the first two characters.
    – nintskari
    Commented Aug 16, 2018 at 8:18
  • @nintskari glad you found your way. just asking: trim() explicitly removes whitespaces at the start and end of a string...are you sure that those leading commas are removed?
    – geozelot
    Commented Aug 16, 2018 at 8:42

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.