July 14, 2023

How to Easily Write a Multiple IF Statement in Power BI using the SWITCH Function

By Nabila Mohamed

Power BI is a versatile and scalable platform that combines self-service and enterprise business intelligence (BI) capabilities. It serves as a comprehensive solution for connecting to diverse data sources and creating compelling visualizations. Data Analysis Expressions (DAX) is the formula expression language employed in Power BI. 

With DAX, you can construct intricate calculations and queries on data residing in the Power BI data model. While DAX does offer the commonly known conditional function, IF, it is generally recommended to limit its usage to one or two conditions to maintain clarity and simplicity since nesting is required for a multiple IF statement – enter the SWITCH function.

SWITCH is a DAX function that has several applications, including easily implementing logic for a multiple IF function that would otherwise be overly complex. This alternative not only provides a more elegant solution but also enhances the readability and maintainability of the measure. By employing the SWITCH function, you can manage complex scenarios involving multiple values.

In this blog, I will present an in-depth exploration of the SWITCH function in DAX. We will explore its distinct features, compare it to the IF function, and learn how to use it for handling multiple conditions. By the end of it, you will have a thorough understanding of the SWITCH function’s capabilities and be equipped to leverage it for robust and concise conditional logic in your DAX measures.

What is the SWITCH Function?

The SWITCH function in Power BI provides a convenient way to evaluate an expression against a list of values and return a corresponding result expression. If you’re familiar with SQL, it is similar to a CASE statement, allowing for versatile conditional logic statements. Below is the syntax required when using SWITCH, as well as a table of each component’s explanation.
SWITCH(<expression>, <value>, <result>[, <value>, <result>]…[, <else>])
Term Definition
expression Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context).
value A constant value is to be matched with the results of the expression.
result Any scalar expression is to be evaluated if the results of the expression match the corresponding value.
else Any scalar expression is to be evaluated if the result of the expression doesn't match any of the value arguments.

How is the SWITCH Function Different From the IF Statement?

The IF function in Power BI allows you to evaluate a condition and return a specific value when the condition is true and a different value when the condition is false. The IF function is useful for handling one or two conditions, but as the number of conditions increases, nesting them becomes necessary. Multiple nested statements can be challenging to read and may lead to overlooking certain conditions. 


This nesting of IF statements not only hampers readability, especially with an increased number of conditions, but it also reduces performance. This is where the SWITCH function offers a superior approach for expressing multiple conditions.

How to Use the SWITCH Function to Write a Multiple Conditional Statement in Power BI

Using SWITCH for String Data Types

  1. Create a new column measure in the appropriate table where your target column resides. Once you have assigned a name to your measure, set it using the following structure:

    
    Measure Name = SWITCH(
        True(),
        {value 1}, {result 1},
        {value 2}, {result 2},
        ...
        {value n}, {result n},
        {else}
    )
    
  1. Just like an if function, specify each condition by equating the column name to the value you want to modify, followed by a comma and the desired replacement value.

  2. Separate each value-result pair with a comma, allowing you to include as many conditions as necessary.

  3. You can optionally include an else condition to account for scenarios where the condition of the expression does not match any of the value arguments. This provides a fallback action when none of the specified values are met.

  4. Finally, close out the function with a closing parenthesis ” )”.


Stock Category = SWITCH(
    True(),
    Calendar[Month]="Jan", "January",
    Calendar[Month] ="Feb", "February",
    Calendar[Month] ="Mar", "March", 
    Calendar[Month] ="Apr", "April", 
    Calendar[Month] ="Jun", "June", 
    Calendar[Month] ="Jul", "July", 
    Calendar[Month] ="Aug", "August", 
    Calendar[Month] ="Sep", "September", 
    Calendar[Month] ="Oct", "October", 
    Calendar[Month] ="Nov", "November", 
    Calendar[Month] ="Dec", "December", 
    ISBLANK(Calendar[Month]),"null"
    ) 

Using SWITCH for Integers

Creating the measure becomes even simpler when the condition value is an integer data type. In such cases, you can omit the True() function altogether and proceed directly to replace the values after the Switch function. It’s important to note that you only need to reference the column name once, and you should not enclose the integer values in quotation marks, as they are treated as numeric values by default.


Stock Category = SWITCH(
      Calendar[Month], 1, "January", 
                       2, "February", 
                       3, "March", 
                       4, "April",  
                       5, "May", 
                       6, "June", 
                       7, "July", 
                       8, "August", 
                       9, "September", 
                       10, "October", 
                       11, "November",  
                       12, "December", 
                       "null"
                       )
 

When working with the SWITCH function, it is possible to have values and results of different data types. However, it is important to ensure that all the result expressions and the else expression are of the same data type. This consistency in data types ensures the proper functioning of the SWITCH function and maintains data integrity throughout your calculations and evaluations.

Practical Example of Using the SWITCH Function in Power BI

In addition to the previous examples showcasing the use of the SWITCH function for aliasing string and integer values, it is worth noting that it can also be employed to create new groupings. 

This can be achieved by combining the SWITCH function with other logical functions (such as AND, OR, NOT), logical operators (such as &&, ||, IN), or comparison operators (such as >, <>, <=) to construct more intricate and sophisticated conditions. This flexibility allows you to handle complex scenarios and define custom categories based on specific criteria.

Side-by-Side Comparison of IF() and SWITCH()

Let’s compare the usage of an IF function and a SWITCH function when implementing conditional logic with more than two conditions using a comparison operator to categorize values.

IF()


Price Group =
IF(
    'Product'[List Price] < 500,
    "Low",
    IF(
        'Product'[List Price] < 1500,
        "Medium",
        "High"
    )
)

SWITCH()


Price Group =
SWITCH(
    'Product'[List Price] < 500, "Low",
    'Product'[List Price] < 1500, "Medium",
     "High"
)

IF Function

When confronted with multiple conditions, the IF function can become cumbersome and less readable due to the need for nested IF statements. This nesting can also negatively impact performance and maintenance.

Switch Function

The SWITCH function offers a more efficient and elegant solution for handling multiple conditions. It allows you to specify multiple value-result pairs within a single function, simplifying the code and enhancing readability. Moreover, the SWITCH function’s design optimizes performance, making it a preferred choice for complex conditional logic scenarios.

Closing

While the IF function can handle multiple conditions, the SWITCH function excels in providing a streamlined and efficient approach, ensuring cleaner code and better performance when dealing with more than two conditions.

SWITCH() is a versatile function that empowers analysts and data professionals to handle complex conditional logic with ease. By understanding and harnessing the capabilities of the SWITCH function, you can streamline your DAX code, enhance readability, and optimize performance. 

The ability to evaluate multiple conditions and return appropriate results empowers data analysts to transform raw data into meaningful insights and actionable information. Moreover, the SWITCH function’s flexibility allows for the creation of dynamic calculations, custom groupings, and advanced calculations, enabling analysts to uncover deeper patterns and trends within their datasets. 

Now that you have gained proficiency in using the SWITCH() function effectively, you are ready to craft logical statements with multiple conditions in Power BI. 

Want to learn more about the Power BI SWITCH() function?

Data Coach is our premium analytics training program with one-on-one coaching from renowned experts.

Accelerate and automate your data projects with the phData Toolkit