Case
Overview
Use case expressions to create a rule-based formula, where different cases have different outputs, similar to "if-else statements" in programming languages.
CASE
statements can include any number ofWHEN
clauses and can optionally include anELSE
clause.- If you omit the
ELSE
clause, cases where none of theWHEN
conditions are met are filled with the valuenull
. - If the data satisfies multiple
WHEN
conditions, the output of the firstWHEN
statement is used.
You can write case statements in two styles.
In the first style, you can use a simplified CASE
statement in which a single attribute is directly compared with values present in the WHEN
clauses. In this example, we populate the attribute company_code
based on the contents of the attribute company_type
.

If company_type
is equal to the string 'Private', then company_code
is populated with the string PRV
. Similarly, a value of 'Public' in company_type
results in a value of 'PUB' for company_code
, and a value of 'Partnership' results in a value of 'PRT'. As we did not include the optional ELSE
clause, company_code
will be null
when company_type
does not match any of the options listed.

The second style of CASE
statement is more flexible, allowing the use of multiple attributes in the WHEN
clauses and more complex conditional statements, such as the array.contains()
function. In the following example, we create a region
column based on whether the value of the state
column is within an array of states. We also ensure that the country column has the value 'USA' before applying these regional rules.


Nested CASE Statements
In some situations, it may be beneficial to use a CASE
statement within a CASE
statement. The following example of a nested CASE statement produces a result similar to the previous unnested example. There is one small difference in the result. Here we distinguish between records that are not in the USA, for which we assign the value 'NON-USA', and records that are within the USA, but do not fall within one of the defined regions, for which we assign the value 'UNKNOWN USA'.


Case Expressions in Scripts
You can also include
CASE
expressions in a script. To do this, useSELECT *
before the beginning of your statement and includeAS <target_attribute>
after theEND
.
Updated over 5 years ago