Sub topic 11
Adding conditional and custom columns
This chapter assumes you can open the Power Query Editor and read the Applied Steps pane. It also assumes you have already set data types and handled nulls, because new columns that compare or combine values depend on both.
Three ways to add a column
The Add Column tab offers several tools. Three of them cover most cleaning work.
| Tool | Best for | What it writes |
|---|---|---|
| Column From Examples | Quick text patterns, such as pulling initials or a domain from an email | A generated M formula you should review |
| Conditional Column | Labels based on simple rules on one or more columns | An `if ... then ... else if ... else` expression |
| Custom Column | Anything the dialog cannot express: several columns, text functions, nested logic | An M expression you write |
All three call Table.AddColumn, so they appear as one new step in Applied Steps. The result is a new column added to the right. The original columns are unchanged.
Conditional Column
Select Add Column > Conditional Column. In the dialog, give the new column a name, then define rules:
- Choose a column, an operator (equals, begins with, is greater than or equal to, and so on), and a value or another column.
- Enter the output for rows that match.
- Use Add Clause for further rules.
- Set the Else value for rows that match none of the rules.
Rules run from top to bottom, and the first match wins. Order matters. If you put "Amount >= 500" above "Amount >= 1000", every large order is labeled with the 500 rule.
Here is the M the dialog generates for a two-rule column, using the data from the previous chapter:
let
Source = #table({"FullName", "Amount"}, {{"Ada Lovelace", 1500}, {"Alan Turing", 300}}),
SplitName = Table.SplitColumn(Source, "FullName", Splitter.SplitTextByDelimiter(" ", QuoteStyle.Csv), {"FirstName", "LastName"}),
AddedSize = Table.AddColumn(SplitName, "OrderSize", each if [Amount] >= 1000 then "Large" else "Small", type text)
in
AddedSizeThree pieces of syntax are worth knowing:
eachstarts a function that runs once per row.[Amount]is shorthand for "the Amount value in the current row".type textat the end sets the data type of the new column.
Custom Column
Select Add Column > Custom Column. The dialog has a name box and a formula box. Double-click a column in the list to insert its [Name] reference. Do not type each in the dialog, because it adds that for you. In the formula bar or Advanced Editor you will see it.
A custom column can do what the Conditional Column dialog cannot. The next query combines three-tier logic, a null check, and a text join:
let
Source = #table(
type table [Customer = text, Region = nullable text, Amount = nullable number],
{{"Ada", "West", 1500}, {"Alan", null, 300}, {"Grace", "East", null}}
),
AddedTier = Table.AddColumn(
Source,
"Tier",
each
if [Amount] = null then "Unknown"
else if [Amount] >= 1000 then "Large"
else if [Amount] >= 500 then "Medium"
else "Small",
type text
),
AddedLabel = Table.AddColumn(
AddedTier,
"Label",
each Text.Combine({[Customer], [Region]}, " - "),
type text
)
in
AddedLabelThe output has these values:
| Customer | Region | Amount | Tier | Label |
|---|---|---|---|---|
| Ada | West | 1500 | Large | Ada - West |
| Alan | null | 300 | Small | Alan |
| Grace | East | null | Unknown | Grace - East |
The diagram shows how one row moves through the Tier expression.
Common errors and how to avoid them
M is case-sensitive
If, Then, and Else fail. Write if, then, and else in lowercase. Column names are also case-sensitive, so [amount] does not match [Amount]. Text comparison is case-sensitive too: [Region] = "west" does not match "West". Clean case first with Text.Lower or Text.Proper, as you did in the text cleaning chapter.
Comparing the wrong types
If Amount is still text, then [Amount] >= 1000 raises an error in every row, because M will not compare text with a number. Set the data type in an earlier step. You can see the problem in the column quality bar, which shows red for errors.
Forgetting the null case
An if expression whose condition is null also raises an error, so a null can break a rule you thought was safe. Test for null first, as the Tier example does. The same applies to joins with &: "Ada" & null returns null, so the whole label disappears. Text.Combine skips null values, which is why Alan keeps his label.
Leaving the new column as type `any`
When you omit the final type argument, the new column has type any and shows an ABC123 icon. It loads, but later steps and the model can treat it inconsistently. Always pass a type: type text, type number, type date, or Int64.Type. In the dialog, set the type from the column header after the step is created. That adds an extra Changed Type step. Passing the type inside Table.AddColumn keeps the query shorter.
Editing the generated code by hand
If you change the formula of a Conditional Column step in the formula bar, the dialog may no longer open from the gear icon. The step still works, but you can only edit it as M. This is a fair trade for logic the dialog cannot express, but it is a one-way change.
Useful expressions for custom columns
These patterns cover most real needs:
- Several conditions:
if [Region] = "West" and [Amount] > 1000 then "Key" else "Standard". Useand,or, andnot. - Text matching:
if Text.Contains([Product], "Pro") then "Premium" else "Basic".Text.Containsis case-sensitive unless you passComparer.OrdinalIgnoreCaseas a third argument. - Math on columns:
[Quantity] * [UnitPrice]. - Dates:
Date.Year([OrderDate])orDate.ToText([OrderDate], "yyyy-MM"). - Defaults:
[Discount] ?? 0returns 0 whenDiscountis null and keeps its value otherwise.
Column From Examples
Select Add Column > Column From Examples, then type the output you want in the first one or two rows. Power Query infers a formula and shows it above the grid. Accept it only after you check the formula against rows that differ from your examples. Inference often fits the sample rows but misses edge cases, such as names with a middle initial. If the formula is wrong, add more example rows or switch to a Custom Column.
Keeping performance in mind
With a database source, a Conditional Column on simple comparisons often folds, which means the work runs in the database rather than in Power Query. A Custom Column that calls many M text or date functions often breaks folding. Right-click the step: if View Native Query is greyed out, the step did not fold. Because folding matters most for large tables, put new columns after filters that do fold and before steps that you know break it.
Exercise
A table has a text column Score that has not been typed yet and a typed number column Bonus that contains nulls. You add the custom column each if [Score] >= 50 then "Pass" else "Fail" and get an error in every row. Name two fixes you need before you add [Score] + [Bonus] as another column.
Show answer
First, set Score to a number type (for example type number, with the en-US locale if the source uses that format) before the column is added, because M cannot compare text with a number. Second, handle the nulls in Bonus, either by replacing nulls with 0 in an earlier step or by writing [Score] + ([Bonus] ?? 0), because adding null to a number returns null.