4

In QGIS (2.10.1 on a Mac), I am trying to make some multiline labels on a map I have with a bunch of trees in them. In the attribute table I have columns with the Latin scientific name, the English name (when one exists), the year the tree was planted etc.

I am labelling the trees in my map with an expression like this:

genus_species + '\n' +
case
    when  "english_species" is not null then  "english_species" + '\n'
end
+ to_string( "planted_year")

This works well for the rows where english_species is not null, however whenever I have a row with no English name, the entire expression just seems to break and nothing is printed, not even the scientific name or the year (which always exists).

I have tried adding a

when  "english_species" is null then ''

But that doesn't work either. The expression just breaks for rows with no value in the field english_species.

2
  • 1
    Have you tried adding an else statement before end (e.g.else ' ')?
    – Joseph
    Commented Oct 13, 2015 at 10:02
  • Yes I have, neither when "english_species" is null then '' or else '' works. Thanks, though.
    – alxvo
    Commented Oct 13, 2015 at 10:05

2 Answers 2

17

So the way QGIS handles NULL when you join strings is that it will convert the result to NULL if any part is NULL (yes I know it's on going debate on if it should or not)

Here is how you handle that using the concat function:

concat( "genus_species", '\n', "english_species", '\n', to_string("planted_year")

The concat function will convert NULL to empty string and join anyway.

1
  • This is still true for QGIS 3.22.3.
    – Homerun_
    Commented Mar 3, 2022 at 12:08
2

You should use string concatenation instead of plus ( symbol ||). It should look more like this:

 CASE
    WHEN "english_species" IS NULL THEN "genus_species" || '\n' || to_string("planted_year")
    ELSE  "genus_species" || '\n' || "english_species" || '\n' || to_string("planted_year")
 END

Update, in 2.10 it is not needed to use || for strings anymore so it is all about need of using ELSE, otherwise the expression is not valid because you end up with + + if it is not the case. So other possible option:

 "genus_species" + '\n' +
 CASE
    WHEN "english_species" IS NOT NULL THEN "english_species" + '\n'
    ELSE '' 
 END
 + to_string("planted_year")

Which in other case makes + '' + and though is valid.

1
  • 1
    Eh, I see now in 2.10 the expression works even with plus. As Joseph mentioned the key seems to be to use ELSE. For some reason as you say if there is no ELSE it does not return any string at all.
    – Miro
    Commented Oct 13, 2015 at 11:57

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