Power Query course · Lesson 12 of 17

Custom and conditional columns

Add calculated columns with the Conditional Column dialog and with Custom Column formulas in M: if/then/else, text tests, nulls, try/otherwise, index columns.

Intermediate 17 min read

So far every step has transformed existing columns. Real reports also need new columns: a VAT amount, a commission rate, a category for each bank transaction, an age band for each employee. Power Query gives you two dialogs for this. Conditional Column builds if-then-else rules by clicking, with no code. Custom Column accepts any M formula. Both add a step that runs again on every refresh, which is what makes them better than a formula typed next to the loaded table.

Conditional Column: rules without code

Example: classify sales reps' monthly revenue into bands for a commission scheme.

ABC
1RepRegionRevenue
2K. OlsenNorth48200
3L. WeberNorth23900
4P. RossiSouth61500
5A. NovakSouth9800

Before: monthly revenue per rep.

  1. Choose Add Column › Conditional Column.
  2. Type Band as New column name.
  3. First rule: Column Name Revenue, Operator is greater than or equal to, Value 50000, Output Gold.
  4. Click Add Clause. Second rule: Revenue is greater than or equal to 20000, Output Silver.
  5. Else: Bronze.
  6. Click OK, then set the column type to Text (newer builds set it for you).
ABCD
1RepRegionRevenueBand
2K. OlsenNorth48200Silver
3L. WeberNorth23900Silver
4P. RossiSouth61500Gold
5A. NovakSouth9800Bronze

After: the rules are checked from top to bottom and the first true rule wins, so the order of clauses matters.

Power Query M
= Table.AddColumn(#"Changed Type", "Band", each if [Revenue] >= 50000 then "Gold" else if [Revenue] >= 20000 then "Silver" else "Bronze", type text)
The dialog writes nested if … then … else expressions.

A few useful details of the dialog:

  • Operators depend on the column type: for text you get equals, does not equal, begins with, does not begin with, ends with, does not end with, contains, does not contain; for numbers and dates you get comparisons.
  • The small ABC 123 button next to Value and Output lets you choose Select a column or Parameter instead of typing a fixed value. Output Select a column › Revenue returns the revenue itself.
  • Re-open the dialog later with the gear icon next to the step. If you edited the M by hand in a way the dialog cannot show, the gear disappears and you must edit in the formula bar.
  • The dialog cannot combine two columns in one rule (Region is North and Revenue ≥ 20000). For that you need a custom column.

Custom Column: formulas in M

Choose Add Column › Custom Column. Type a New column name, then the Custom column formula. Double-click a name in Available columns to insert it in square brackets. A green tick at the bottom says No syntax errors have been detected. Recent builds also have a Data type box in the dialog; set it, otherwise the new column has type Any.

Excel formulaM custom column
=B2*0.24[Amount] * 0.24
=A2&" "&B2[First name] & " " & [Last name]
=IF(C2>=50000,"Gold","Other")if [Revenue] >= 50000 then "Gold" else "Other"
=AND(B2="North",C2>=20000)[Region] = "North" and [Revenue] >= 20000
=ROUND(C2*0.03,2)Number.Round([Revenue] * 0.03, 2)
=YEAR(D2)Date.Year([Hire date])
=TEXT(D2,"yyyy-mm")Date.ToText([Hire date], "yyyy-MM")
=IFERROR(C2/D2,0)try [Revenue] / [Target] otherwise 0
Watch out. M is case-sensitive for everything: function names (Text.Upper, not text.upper), column names ([revenue] is not [Revenue]), and the keywords if, then, else, and, or, not, try, otherwise, which must be lowercase. Most custom column errors are a capital letter in the wrong place.

A commission with two conditions

Power Query M
= Table.AddColumn(#"Added Band", "Commission", each
    if [Region] = "North" and [Revenue] >= 20000 then [Revenue] * 0.05
    else if [Revenue] >= 50000 then [Revenue] * 0.04
    else [Revenue] * 0.02,
    type number)
North reps above 20,000 earn 5%, others above 50,000 earn 4%, everyone else 2%.

Results on the sample: K. Olsen 2,410 (5% of 48,200), L. Weber 1,195, P. Rossi 2,460 (4% of 61,500), A. Novak 196.

Categorising bank transactions by keyword

ABC
1DateDescriptionAmount
22026-05-02CARD 7731 SHELL STATION 044-58.4
32026-05-03SEPA IN ACME PAYROLL MAY2410
42026-05-06CARD 7731 LIDL 2231-84.15
52026-05-07DD ELECTRICITY CO-96

Before: a bank statement with free-text descriptions.

Power Query M
= Table.AddColumn(#"Changed Type", "Category", each
    let d = Text.Upper([Description]) in
    if Text.Contains(d, "PAYROLL") then "Salary"
    else if Text.Contains(d, "SHELL") or Text.Contains(d, "BP ") then "Fuel"
    else if Text.Contains(d, "LIDL") or Text.Contains(d, "ALDI") then "Groceries"
    else if Text.StartsWith(d, "DD ") then "Bills"
    else "Other",
    type text)
A let inside the formula stores the uppercased description once; Text.Contains and Text.StartsWith test it.
ABCD
1DateDescriptionAmountCategory
22026-05-02CARD 7731 SHELL STATION 044-58.4Fuel
32026-05-03SEPA IN ACME PAYROLL MAY2410Salary
42026-05-06CARD 7731 LIDL 2231-84.15Groceries
52026-05-07DD ELECTRICITY CO-96Bills

After: each transaction categorised. A long keyword list is better kept in an Excel table and matched with a merge or a function.

Tip. When the rules grow beyond a dozen keywords, move them to a two-column Excel table (Keyword, Category) that users can maintain. A custom function then finds the first keyword contained in the description; you will build one in Parameters and custom functions.

Nulls in calculations

In M, any arithmetic with null returns null: null + 5 is null, and null * 0.24 is null. Comparisons are also tricky: null > 0 is null, which if treats as an error. Guard against nulls explicitly:

Power Query M
= Table.AddColumn(#"Changed Type", "Net pay", each (if [Gross] = null then 0 else [Gross]) - (if [Deductions] = null then 0 else [Deductions]), type number)
Treat missing values as zero. In recent versions the shorter form ([Gross] ?? 0) does the same.

try … otherwise

try evaluates an expression and catches errors. otherwise gives the fallback, like IFERROR in Excel. Use it for conversions that can fail, such as reading a number from a free-text field:

Power Query M
= Table.AddColumn(#"Changed Type", "Qty", each try Number.From([Qty text]) otherwise null, type nullable number)
Values that are not numbers become null instead of Error.
Watch out. Do not wrap everything in try … otherwise 0. Hiding errors with zeros makes totals wrong in a way nobody notices. Use null as the fallback, and look at how many rows got it.

Index columns

Add Column › Index Column numbers the rows From 0, From 1 or with a Custom start and increment. Uses: a stable row number before sorting, a line number within an invoice (combine with Group By and All Rows), or a key to compare each row with the previous one by merging the table with itself on Index and Index - 1.

Duplicate Column and Column From Examples

Add Column › Duplicate Column copies a column so you can transform the copy and keep the original. Add Column › Column From Examples writes the formula for you from typed examples (see Cleaning text and numbers in Power Query); it is a good way to learn M functions, since you can read the formula it produced.

Note. On the Mac and in Excel for the web the Custom Column and Conditional Column dialogs work the same way; IntelliSense (the suggestion list while typing a formula) is most complete in the Windows version.

Check yourself

1. In a Conditional Column with clauses >= 20000 then Silver and >= 50000 then Gold, in that order, what does 61500 get?

2. Which M expression is valid?

3. What is null * 0.24 in M?

4. Which is the M equivalent of IFERROR?

5. What can a Custom Column do that the Conditional Column dialog cannot?