Using the CASE and WHEN logical function in Tableau with examples


The Tableau CASE and WHEN keyword is used to create a logical statement with your dimension or measure variable(s) to see if it match a certain condition(s).

When the specified condition occurs, CASE will return the value you specify as the return value in the statement.

You can have one or more conditions when defining the CASE function as your calculated field formula.

Let’s see an example of using the CASE function to create a calculated field.

The following dataset contains sales records of a fictional office supplies company:

SalesData.csv

There’s a City dimension variable in the dataset that shows in what city the sales is recorded:

City:
- Edinburgh
- London
- Newcastle

Using Tableau WHEN function, you can encode the cities using numbers as follows:

  • Edinburgh encoded as 1
  • London encoded as 2
  • Newcastle encoded as 3

Right-click anywhere on the Data pane and select the Create Calculated Field… option.

Name the Calculated Field as Encoded City and write the following formula into the field:

CASE [City] WHEN "Edinburgh" THEN 1
WHEN "London" THEN 2
WHEN "Newcastle" THEN 3 END

The above CASE statement reads:

  • When the City value equals Edinburgh then return 1
  • When the City value equals London then return 2
  • When the City value equals Newcastle then return 3

The CASE function also requires the END keyword to indicate the end of the function.

Since you’re creating a dimensional calculated field, you need to right-click on the Encoded City variable and select Convert to Dimension.

Finally, drag the Encoded City and the City variables into the Rows shelf of your Sheet.

You’ll see the table output generated as follows:

As you can see, the City values have been encoded using the CASE function with multiple conditions.

You can also replace the third WHEN statement with an ELSE statement like this:

CASE [City] WHEN "Edinburgh" THEN 1
WHEN "London" THEN 2
ELSE 3 END

The ELSE statement will be considered as the default return value should the WHEN conditions are not fulfilled.

If you want to inspect the calculated field, you can view and download the Workbook for this tutorial here:

Tableau Case When Example

And that’s how you can use the CASE - WHEN statement in Tableau. Good work! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.