# Chris Webb's BI Blog

Analysis Services, MDX, PowerPivot, DAX and anything BI-related

## Conditional logic in Power Query

Writing a simple if statement in Power Query’s M expression language is straightforward. Using an Excel table called Input that contains a single value as the starting point:

The following query shows how to use an if … then … else statement to test whether the value from the table is equal to 5:

`let`

`    Source = Excel.CurrentWorkbook(){[Name="Input"]}[Content],`

`    InputValue = Source{0}[Input],`

`    IfStatement = if InputValue=5 `

`                    then "The number is five" `

`                    else "The number is not five"`

`in`

`    IfStatement`

What about more complex conditional logic? The M language doesn’t include anything like a case statement, but it is possible to write the equivalent of one quite easily.

Here’s an example of a simple case statement:

`let`

`    Source = Excel.CurrentWorkbook(){[Name="Input"]}[Content],`

`    InputValue = Source{0}[Input],`

`    CaseValues = {`

`                    {1, "First"},`

`                    {2, "Second"},`

`                    {3, "Third"},`

`                    {4, "Fourth"},`

`                    {5, "Fifth"},`

`                    {InputValue, "Else condition"}`

`                },`

`    SimpleCase = List.First(List.Select(CaseValues, each _{0}=InputValue)){1}`

`in`

`    SimpleCase`

This works as follows:

• The CaseValues step defines a list containing six items, each of which is itself a list containing a number and some text. The number is the value to compare to the input value, and the text is what will be returned if the number does match the input value.
• The last item in the CaseValues list contains the input value, so this will be returned where the input value matches none of the preceding values
• The SimpleCase step uses List.Select() to filter the list in CaseValues so that only the items in the list where the input value matches the number in the list.
• Since List.Select itself returns a list, this list is then passed to List.First() to get the first item in the list returned by List.Select (there should only be one item in the list in this particular query), and then {1} returns the text from that item. This is the output of the query.

You can write a searched case expression in a very similar way, by declaring functions that return boolean values instead of using numbers as follows:

`let`

`    Source = Excel.CurrentWorkbook(){[Name="Input"]}[Content],`

`    InputValue = Source{0}[Input],`

`    CaseValues = {`

`    { (x)=>x<10, "Less than 10"},`

`    { (x)=>x<20, "Less than 20"},`

`    { (x)=>x<30, "Less than 30"},`

`    { (x)=>x<40, "Less than 40"},`

`    { (x)=>x<50, "Less than 50"},`

`    { (x)=>true, "Else condition"}`

`    },`

`    SimpleCase = List.First(List.Select(CaseValues, each _{0}(InputValue))){1}`

`in`

`    SimpleCase`

In this query the CaseValues step contains a list of lists, where each item in the list consists of list containing a function and a text value. List.Select calls each function and only returns the items where the function returns true, and finally the text from the first item that List.Select returns is the output of the query.

Written by Chris Webb

March 10, 2014 at 9:00 am

Posted in Power Query

### 26 Responses

1. […] Webb posted another excellent Power Query blog this morning, Conditional Logic in Power Query, where Chris shows how to implement a pseudo-Case statement in Power […]

• Chris,

That’s very clever! I use stacked else ifs, but that’s not as cool as your solution. For example, as a custom function, stacking else ifs would look like:

let
Source = (x)=>
if x<10 then "Less than 10"
else if x<20 then "Less than 20"
else if x<30 then "Less than 30"
else if x<40 then "Less than 40"
else if x<50 then "Less than 50"
else "Greater than or equal to 50"
in
Source

Colin Banfield

March 10, 2014 at 4:52 pm

• I’m prepared to admit that this is a bit *too* clever – and that the stacked ifs is probably more maintainable – but this was as much about learning what’s possible in M as solving a real problem.

Chris Webb

March 10, 2014 at 5:41 pm

• In fact, I wonder whether the stacked ifs might perform better too…

Chris Webb

March 10, 2014 at 5:42 pm

• Performance might be better with stacked else ifs because you avoid multiple function calls. However, my takeaway from your post is, as you said – learning what’s possible in M to solve real problems. The pattern looks like something that can be adapted for other scenarios. It’s ironic when I think that I started using M to fill what I thought were gaps in PQ, and I’ve learned much more than I would have if those gaps weren’t there. I hope to post some of these solutions when I figure out an appropriate outlet.

Colin Banfield

March 10, 2014 at 6:53 pm

2. […] a short follow-up to my last post on conditional logic in M. After that post went live, Ehren Vox of the Power Query team made a good suggestion on Twitter: […]

3. […] a short follow-up to my last post on conditional logic in M. After that post went live, Ehren Vox of the Power Query team made a good suggestion on Twitter: […]

4. I just had a case where I had this Chinese textual column (number of CPU cores) I wanted to make numerical. I used the following approach using List.ReplaceMatchingItems() after looking for a way to do a switch statement in M, which seems somewhat similar to your approach, if probably less flexible:

InsertedCustom = Table.ExpandListColumn(Table.AddColumn(ChangedType, “cores”, each List.ReplaceMatchingItems ({[核心数]}, {{“单核心”, 1},{“双核心”, 2},{“四核心”, 4}})), “cores”)

The original column just contained string values while List.ReplaceMatchingItems() required a list, so I first had to cast the column value to a list (-> {[核心数]} ), then cast the result back to a regular non-list value, hence the unfortunate Table.ExpandListColumn(). Too bad it doesn’t just work with non-lists, but as a one-liner it’s fair enough for my purposes here.

tycho01

March 16, 2014 at 11:49 am

5. Hi Chris! Thank you for your excellent posts about Power Query. I look forward to buy your book when it will be updated.

I also have a question today about some conditional logic which is difficult to solve with my current knowledge of M.

The case is something like:

Brand1 blank blank
blank Category1 blank
blank blank SKU1
Brand2 blank blank
blank Category2 blank
blank blank SKU2

So I need something which can understand if value in the first column isn’t blank and copy value to the same row in column 2 but from second down row in column 2. And then for column 3 also.

Brand1 Category1 SKU1
blank Category1 SKU1
blank blank SKU1
Brand2 Category2 SKU2
blank Category2 SKU2
blank blank SKU2

Then I will be able to use just fill down for all column to get the result:

Brand1 Category1 SKU1
Brand1 Category1 SKU1
Brand1 Category1 SKU1
Brand2 Category2 SKU2
Brand2 Category2 SKU2
Brand2 Category2 SKU2

Mer

December 5, 2014 at 9:21 am

• Won’t the Fill Up/Down buttons do this for you?

Chris Webb

December 5, 2014 at 11:30 am

• If I use Fill Down and then Up here, then I have a problem which you can see below:

Brand1 Category1 SKU1
Brand1 Category1 SKU1
Brand1 Category1 SKU1
Brand2 Category1 SKU1
Brand2 Category2 SKU2
Brand2 Category2 SKU2

First row is ok, but then Category1 dropped to the Brand2 where it shouldn’t be. If I use Fill Up first, then Category2 will be in the Brand1’s row.

Actually I realized that I don’t need it anymore due to specific properties of my data…

But it’s still actual for the future what would you do in that situation?

Mer

December 5, 2014 at 12:16 pm

• Sorry for the late reply, I’ve been very busy over the last few days. This is an interesting problem, but I think it is easy to solve. You load the data in as originally shown, then do a fill down on Category and Brand. The important final step, though, is to filter out all but the rows that originally had a SKU on. Here’s the code:

let
Source = Excel.CurrentWorkbook(){[Name=”Table3″]}[Content],
#”Filled Down” = Table.FillDown(Source,{“Brand”}),
#”Filled Down1″ = Table.FillDown(#”Filled Down”,{“Category”}),
#”Filtered Rows” = Table.SelectRows(#”Filled Down1″, each ([SKU] null))
in
#”Filtered Rows”

Chris Webb

December 10, 2014 at 10:04 pm

• Thanks Chris! I already did exactly like this. =) Luckily I don’t need rows where SKU is BLANK but what is I’d need them? Miguel found and excellent solution and I still trying to figure out how it works… It’s on the link below.

Mer

December 11, 2014 at 7:38 am

6. Also it would be good if you know something to unpivot a table with a few horizontal and vertical headings.

This approach – http://wessexbi.wordpress.com/2014/02/27/unpivot-nested-headings-with-power-query/ – doesn’t work because after Transpose function I still have a few headings.

Mer

December 5, 2014 at 10:29 am

• Can you give me a specific example of what you need?

Chris Webb

December 5, 2014 at 11:30 am

• To simplify, I have a table something like:

Tons Units USD
2010 2011 2012 2010 2011 2012 2010 2011 2012
Brands Categories

And a lot of values inside of it.

So I need:

Brands Categories Measures Period

Mer

December 5, 2014 at 11:56 am

• Sorry. I need:

Brands Categories Period Tons Units USD

Mer

December 5, 2014 at 11:58 am

• Also I lost all my spaces here after click a button “Post Comment”…

So table actually lloks like

————————–Tons—————-Units—————-USD
————————–2010 2011 2012 2010 2011 2012 2010 2011 2012
Brands Categories

Mer

December 5, 2014 at 12:01 pm

• I suppose I found something useful considering this issue:

http://www.excelguru.ca/blog/2014/09/24/un-pivoting-with-subcategories-in-power-query/

I will try it and let your know.

Please look at the other two questions.

Mer

December 5, 2014 at 2:02 pm

7. Ooh, this M language is tough…

Sorry if I’m too bothering you…

Is it possible also in Power Query to do Fill Down function only for columns that *have* text in a first or second row. I don’t know which rows is it. So I need condition like:

1) Take table
2) Find columns that don’t have *null* in a first row or in a second row.
3) Fill down those columns.

Mer

December 5, 2014 at 1:38 pm

• I already broke my mind. =( Any ideas how to solve it?

Mer

December 8, 2014 at 7:22 am

• Also I did a misprint in a question. “The sentence I don’t know which rows is it”. should be “I don’t know which columns is it”.

Mer

December 8, 2014 at 7:24 am

8. The problem is that I don’t know how to do the second step here.

Theoretically we have a Table.SelectColumns function but how to write it with condition?

Mer

December 8, 2014 at 8:15 am

9. […] to be fair, you could go the route of building a kind of case statement, as Chris Webb has done here.  In actual fact, you probably should do that if you want something that is lean and mean, and the […]

10. […] Query doesn’t have a “Select Case” concept.  I Googled it and found one of Chris Webb’s blog posts on the topic.  He wrote his own version of Select Case, but it looked too hard to me.  So this is the way I […]