Using CASE in the QGIS Expression Engine


I recently found out about the fact that you can use CASE in QGIS expressions.
This is exciting mostly because it can greatly simplify conditional statements and make them readable and easy to understand while avoiding using a lot of if functions wrapped around each other.

The basic structure of a CASE statement is pretty simple:

CASE

    WHEN condition THEN result

    WHEN other condition THEN other result

    ELSE default result

END

 

That same expression using the if  function will look something like this:

if(condition,result,
    if(other condition, other result, default result))

It's shorter, but harder to read, especially if you keep stacking rules. Imagine the same statement with 10 conditions, that would be 10 if functions wrapped around each other, the result becoming less readable with each added condition, the CASE statement will just get longer but remain just as readable.

Let's do an example, we'll color the Natural Earth Countries layer by continent, once with a CASE statement and once with wrapped if  functions. You could get the same effect with categorized symbols, but if you've read some of my other posts about the expression engine, you can see that combining expression in your workflow can create new and wonderful options for styling and settings.

Start by loading the layer and opening an expression window for the simple fill, fill color.


We then create an expression that return a hex color string for each continent, this is the expression I wrote, using a varying color palette.



      

    CASE
        WHEN
"continent" = 'Africa' THEN '#f94144'
        WHEN
"continent" = 'Antarctica' THEN '#f3722c'
        WHEN
"continent" = 'Asia' THEN '#f8961e'
        WHEN
"continent" = 'Europe' THEN '#f9c74f'
        WHEN
"continent" = 'North America' THEN '#90be6d'
        WHEN
"continent" = 'Oceania' THEN '#43aa8b'
        WHEN
"continent" =  'South America' THEN '#4d908e'
        ELSE
'#0a0a0a'
      END

The same expression using the if functions will look like this:


 

if("continent" = 'Africa','#f94144',
if("continent" = 'Antarctica','#f3722c',
if("continent" = 'Asia','#f8961e',
if("continent" = 'Europe','#f9c74f',
if("continent" = 'North America','#90be6d',
if("continent" = 'Oceania','#43aa8b',
if("continent" =  'South America','#4d908e',
'#0a0a0a'))))))) 


It's shorter, but harder to read and debug as you add more conditions.

 

This is just a simple example of using CASE to replace the if function, we can also use CASE statements to replace more complex conditions, like the one used to change the countries color in my post about map themes.



Comments