top of page

You are learning Power Query in MS Excel

How to use conditional logic with functions like IF or SWITCH in Power Query M?

Power Query M offers two main ways to implement conditional logic:

1. IF function: This is the most basic approach for applying logic based on a single condition.

2. SWITCH function: This is a more versatile option for handling multiple conditions and assigning different outputs based on those conditions.

Using the IF Function:

The IF function follows this syntax:

```
if [condition] then [value_if_true] else [value_if_false]
```

* [condition]: This is a logical expression that evaluates to TRUE or FALSE.
* [value_if_true]: The value returned if the condition is TRUE.
* [value_if_false]: The value returned if the condition is FALSE.

Example:

Let's say you have a column named "Sales" and want to categorize sales amounts into different ranges. You can use an IF statement like this:

```
Sales Category =
if [Sales] > 1000 then "High"
else if [Sales] > 500 then "Medium"
else "Low"
```

This will create a new column named "Sales Category" that assigns values based on the sales amount.

Using the SWITCH Function:

The SWITCH function allows for evaluating multiple conditions and returning corresponding values. It follows this syntax:

```
M.Switch(expression, {value1, result1}, {value2, result2}, ..., {valueN, resultN}, [default])
```

* [expression]: The value you want to evaluate against the conditions.
* [{value1, result1}, {value2, result2}, ..., {valueN, resultN}]: Pairs of possible values for the expression and the corresponding results to return if the value matches.
* [default]: (Optional) The value to return if none of the conditions match.

Example:

Building on the previous example, you can achieve the same categorization using SWITCH:

```
Sales Category =
M.Switch(
[Sales],
{1001, "High"},
{501, "Medium"},
{"Low"} // Default value for any value less than or equal to 500
)
```

This approach offers a cleaner way to handle multiple conditions.

Choosing Between IF and SWITCH:

* Use IF for simple conditions with a true/false outcome.
* Use SWITCH for handling multiple conditions and assigning different outputs.

Additional Tips:

* You can nest IF statements or combine them with SWITCH for complex logic.
* Power Query also offers other logical functions like AND, OR, and NOT for building more intricate conditions.

By understanding IF and SWITCH functions, you can effectively implement conditional logic in your Power Query M queries, transforming and categorizing your data based on specific criteria.

bottom of page