Applying OR, AND, and SWITCH logic
Excel’s IF, OR and AND all have counterparts in M, which are written as keywords rather than functions. SWITCH has no counterpart, but a short function can rebuild it. This page shows each of them on the same data.
The sample data
Section titled “The sample data”Suppose a production company keeps its crew bookings in an Excel table named CrewBookings:
| Booking Code | Production | Role | Day Rate | Hours |
|---|---|---|---|---|
| DCAM0412 | The Lantern Keepers | Focus puller | 520.00 | 11 |
| WLGT0418 | Quarry Lane | Gaffer | 610.00 | 12 |
| FART0420 | Saltmarsh | Production designer | 1,250.00 | 9 |
| DSND0425 | Quarry Lane | Boom operator | 455.00 | 10 |
| WCAM0431 | Saltmarsh | Director of photography | 1,150.00 | 12 |
| DCOS0436 | The Lantern Keepers | Costume assistant | 310.00 | 9 |
| Dlgt0440 | Saltmarsh | Electrician | 395.00 | 11 |
| FSND0447 | The Lantern Keepers | Sound mixer | 780.00 | 8 |
Hours is the length of the crew member’s longest shooting day that week. Each booking code is built from three parts:
- The first letter gives the contract type: D for daily, W for weekly and F for a fixed fee.
- The next three letters give the department: CAM for camera, LGT for lighting, ART for art, SND for sound and COS for costume.
- The four digits are the booking number.
The code Dlgt0440 was typed with its department in lowercase. It matters in the SWITCH section.
Load the data into Power Query:
- Select any cell in the table, and create a new query From Table/Range.
- Set the type of Day Rate to Decimal Number and the type of Hours to Whole Number.
If, then, else
Section titled “If, then, else”To label each booking with its contract type, Excel would use nested IF functions on the first letter of the code:
=IF(LEFT([@[Booking Code]],1)="D","Daily",IF(LEFT([@[Booking Code]],1)="W","Weekly","Fixed fee"))In Power Query, add a column for it:
- On the Add Column tab, choose Custom Column.
- Name the column Contract.
- Enter this formula:
= if Text.Start([Booking Code], 1) = "D" then "Daily" else if Text.Start([Booking Code], 1) = "W" then "Weekly" else "Fixed fee"Text.Start returns the given number of characters from the start of the text, so here it returns the first letter. M writes if, then and else as lowercase keywords, and a further test goes after an else as another if, which reads more easily than Excel’s nested brackets. Any letter other than D or W falls through to Fixed fee.
The new column looks like this, with the Day Rate and Hours columns left out here:
| Booking Code | Production | Role | Contract |
|---|---|---|---|
| DCAM0412 | The Lantern Keepers | Focus puller | Daily |
| WLGT0418 | Quarry Lane | Gaffer | Weekly |
| FART0420 | Saltmarsh | Production designer | Fixed fee |
| DSND0425 | Quarry Lane | Boom operator | Daily |
| WCAM0431 | Saltmarsh | Director of photography | Weekly |
| DCOS0436 | The Lantern Keepers | Costume assistant | Daily |
| Dlgt0440 | Saltmarsh | Electrician | Daily |
| FSND0447 | The Lantern Keepers | Sound mixer | Fixed fee |
Suppose the request is for every booking that is either on Saltmarsh or in the camera department. Filtering Production to Saltmarsh and then filtering the department to camera does not answer it, because the two filters together keep only Saltmarsh’s camera bookings. The camera bookings on other productions, and Saltmarsh’s bookings in other departments, are lost.
In an Excel table, the usual answers are Advanced Filter, or a helper column with a formula like this one, filtered to TRUE:
=OR([@Production]="Saltmarsh",MID([@[Booking Code]],2,3)="CAM")Neither helps when the data comes from a database, a web page or a text file rather than a worksheet table. Power Query can do the same job whatever the source.
Because a filter would drop rows that are needed, the test goes into a new column, which checks each row in turn:
- On the Add Column tab, choose Custom Column.
- Name the column Match.
- Enter this formula:
= if [Production] = "Saltmarsh" or Text.Middle([Booking Code], 1, 3) = "CAM" then "Meets criteria" else "No match"Text.Middle returns the given number of characters from a starting position. Positions in M count from 0, so position 1 is the second character, where Excel’s MID would call it position 2. The or keyword returns true when either test is true, which is what Excel’s OR does.
Click OK. Each row on Saltmarsh, or with CAM as its department, shows Meets criteria:
| Booking Code | Production | Role | Contract | Match |
|---|---|---|---|---|
| DCAM0412 | The Lantern Keepers | Focus puller | Daily | Meets criteria |
| WLGT0418 | Quarry Lane | Gaffer | Weekly | No match |
| FART0420 | Saltmarsh | Production designer | Fixed fee | Meets criteria |
| DSND0425 | Quarry Lane | Boom operator | Daily | No match |
| WCAM0431 | Saltmarsh | Director of photography | Weekly | Meets criteria |
| DCOS0436 | The Lantern Keepers | Costume assistant | Daily | No match |
| Dlgt0440 | Saltmarsh | Electrician | Daily | Meets criteria |
| FSND0447 | The Lantern Keepers | Sound mixer | Fixed fee | No match |
The camera booking on Saltmarsh, WCAM0431, meets both conditions and also shows Meets criteria, because one true test is enough.
Where there are many tests, List.AnyTrue gives the same answer from a list of them, written inside curly braces:
= if List.AnyTrue({[Production] = "Saltmarsh", Text.Middle([Booking Code], 1, 3) = "CAM"}) then "Meets criteria" else "No match"To return only the matching rows, filter the Match column to keep Meets criteria. Here the rows stay, so that the next section can use them all.
Filtering column by column already gives AND logic, because each filter narrows the rows left by the one before. That only works, though, when the aim is to remove rows. To label the rows that meet every condition while keeping all the data, use the and keyword, which returns true only when both tests are true.
Suppose a crew member is eligible for overtime when they are on a daily contract and their longest day ran over ten hours. In Excel:
=AND([@Contract]="Daily",[@Hours]>10)In Power Query, add a custom column named Overtime with this formula:
= if [Contract] = "Daily" and [Hours] > 10 then "Eligible" else "Not eligible"The test [Hours] > 10 needs Hours to be a number, which is why its type was set when the data was loaded. Comparing text with a number in M raises an error rather than returning false.
| Booking Code | Contract | Hours | Overtime |
|---|---|---|---|
| DCAM0412 | Daily | 11 | Eligible |
| WLGT0418 | Weekly | 12 | Not eligible |
| FART0420 | Fixed fee | 9 | Not eligible |
| DSND0425 | Daily | 10 | Not eligible |
| WCAM0431 | Weekly | 12 | Not eligible |
| DCOS0436 | Daily | 9 | Not eligible |
| Dlgt0440 | Daily | 11 | Eligible |
| FSND0447 | Fixed fee | 8 | Not eligible |
DSND0425 is on a daily contract, but its longest day was exactly ten hours, so it is not over ten and the booking is not eligible. The weekly bookings ran over ten hours but fail the first test. As with or, List.AllTrue takes a list of tests and returns true only when every one of them is true.
Labelling rather than filtering keeps the full dataset in the query, so later steps can still use the rows that did not match. With its steps renamed, the query so far reads like this in the Advanced Editor:
let Source = Excel.CurrentWorkbook(){[Name="CrewBookings"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source, {{"Day Rate", type number}, {"Hours", Int64.Type}}), #"Added Contract" = Table.AddColumn(#"Changed Type", "Contract", each if Text.Start([Booking Code], 1) = "D" then "Daily" else if Text.Start([Booking Code], 1) = "W" then "Weekly" else "Fixed fee", type text), #"Added Match" = Table.AddColumn(#"Added Contract", "Match", each if [Production] = "Saltmarsh" or Text.Middle([Booking Code], 1, 3) = "CAM" then "Meets criteria" else "No match", type text), #"Added Overtime" = Table.AddColumn(#"Added Match", "Overtime", each if [Contract] = "Daily" and [Hours] > 10 then "Eligible" else "Not eligible", type text)in #"Added Overtime"SWITCH
Section titled “SWITCH”Excel’s SWITCH compares one expression against a list of values and returns the result paired with the first match, with an optional default at the end. It is easier to read and maintain than several nested IF functions. Its syntax is:
=SWITCH(expression,value_1,result_1,[value_2,result_2],...,[default])It suits codes in which each part means something, such as the department letters in a booking code. In Excel, one formula decodes them:
=SWITCH(MID([@[Booking Code]],2,3),"CAM","Camera","LGT","Lighting","ART","Art","SND","Sound","COS","Costume","Unknown")1. Write a SWITCH function
Section titled “1. Write a SWITCH function”M has no SWITCH, but a record can hold the pairs, and a short function can look the code up in it:
- Create a blank query: choose From Other Sources and then Blank Query.
- Name the query fnDepartment.
- On the Home tab, open the Advanced Editor.
- Enter this code:
(code as text) as text => let Departments = [ CAM = "Camera", LGT = "Lighting", ART = "Art", SND = "Sound", COS = "Costume" ], Result = Record.FieldOrDefault(Departments, code, "Unknown") in ResultThis is how the function works:
Departmentsis a record. Each field name, such asCAM, is a value to look for, and the field’s value, such as"Camera", is the result to return for it.- Further pairs go inside the square brackets, separated by commas, and there can be as many as needed.
Record.FieldOrDefaultreturns the value of the field whose name matchescode. When no field matches, it returns its third argument,"Unknown", which plays the part of the default at the end ofSWITCH.
When the function is complete:
- Click Done.
- On the Home tab, choose Close & Load.
2. Use the function
Section titled “2. Use the function”Now use fnDepartment to add a department to each booking. Open the crew bookings query again, then:
- On the Add Column tab, choose Custom Column.
- Name the column Department.
- Enter this formula, which passes the second to fourth characters of the code to the function:
= fnDepartment(Text.Middle([Booking Code], 1, 3))The result looks like this, with the earlier columns left out here:
| Booking Code | Role | Department |
|---|---|---|
| DCAM0412 | Focus puller | Camera |
| WLGT0418 | Gaffer | Lighting |
| FART0420 | Production designer | Art |
| DSND0425 | Boom operator | Sound |
| WCAM0431 | Director of photography | Camera |
| DCOS0436 | Costume assistant | Costume |
| Dlgt0440 | Electrician | Unknown |
| FSND0447 | Sound mixer | Sound |
Every booking returns a department except Dlgt0440, which shows Unknown. Its department letters are lgt, and field names in M are case-sensitive, so lgt does not match LGT. Excel’s SWITCH ignores case when it compares text, so the same code would return Lighting there.
To see the function respond to changes in the data:
- On the Home tab, choose Close & Load.
- On the worksheet, change the department letters of any booking code to another department, such as DCAM0412 to DART0412, and refresh the table.
The function reads the new letters on the refresh and returns the matching department.
To accept lowercase letters as well, convert the letters to uppercase before passing them to the function:
- Right-click the crew bookings query in the Queries & Connections pane and choose Edit.
- Select the step that added Department and click its gear icon.
- Change the formula to:
= fnDepartment(Text.Upper(Text.Middle([Booking Code], 1, 3)))- Click OK.
- On the Home tab, choose Close & Load.
The booking Dlgt0440 now returns Lighting.