Sub topic 15
Adding custom and conditional columns
Power Query can add columns whose values come from a rule you define. This chapter covers the two main ways to do that: the Custom Column dialog, which takes any M expression, and the Conditional Column dialog, which builds if/then/else logic without typing code.
Prerequisites assumed: you can import a table into the Power Query Editor, you understand Applied Steps, you know the basic data types, and you have seen M code in the formula bar. If any of these is unfamiliar, review the earlier chapters on the editor, data types, and M basics first.
When to add a column in Power Query
Excel formulas in the worksheet recalculate on the loaded result. A column added in Power Query is computed during refresh and loaded as plain values. That gives you three benefits:
- The rule is stored in the query, so it is applied the same way every refresh.
- The loaded table has no formulas to break or fill down.
- Later steps, such as Group By or merge, can use the new column.
Use a worksheet formula instead when the result must react immediately to cells outside the query, such as a threshold a user types on a sheet. (Parameters, covered in a later chapter, can also supply such values to a query.)
Custom Column
Choose Add Column > Custom Column. Enter a new column name and a formula. Column names appear in the formula as [ColumnName]. Each formula is evaluated once per row.
The dialog writes a step that calls Table.AddColumn. A column added this way has no type, so it is marked as type any (the ABC/123 icon). Set a type, either by changing it afterward or by passing a type as the fourth argument.
let
Source = Excel.CurrentWorkbook(){[Name="SalesClean"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Quantity", Int64.Type}, {"UnitPrice", type number}}),
WithTotal = Table.AddColumn(Typed, "LineTotal", each [Quantity] * [UnitPrice], type number)
in
WithTotalThe word each is shorthand for a function that takes one argument, the current row. [Quantity] means "the Quantity field of that row". Without the fourth argument, the new column would have type any, and later steps could behave unexpectedly.
Common expressions
| Goal | Expression |
|---|---|
| Combine text | `[First] & " " & [Last]` |
| Number to text | `Text.From([OrderID])` |
| Extract year | `Date.Year([Date])` |
| Month name | `Date.MonthName([Date])` |
| Days between dates | `Duration.Days([Shipped] - [Ordered])` |
| Round | `Number.Round([Amount], 2)` |
| Text length | `Text.Length([Code])` |
Conditional Column
Choose Add Column > Conditional Column for tiered rules. You pick a column, an operator, a value, and the output. You can add several Else If clauses and a final Otherwise. The generated M uses if ... then ... else.
let
Source = Excel.CurrentWorkbook(){[Name="SalesClean"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Amount", type number}}),
Band = Table.AddColumn(
Typed,
"SizeBand",
each if [Amount] >= 10000 then "Large"
else if [Amount] >= 1000 then "Medium"
else "Small",
type text
)
in
BandThe conditions are checked from top to bottom. The first true condition wins, so list the most restrictive test first. If you wrote [Amount] >= 1000 first, every large amount would be labeled "Medium".
Operators in M
M uses = for equality, not ==, and <> for "not equal". Text comparisons are case-sensitive, so "north" = "North" is false. Compare Text.Lower([Region]) = "north" when case may vary. Combine tests with and, or, and not, all in lowercase.
Handling nulls in conditions
A blank cell becomes null. Comparing null with a number does not behave like comparing zero: null >= 1000 is false, so a null amount falls through to the else branch and is labeled "Small". Decide how to treat blanks explicitly:
let
Source = Excel.CurrentWorkbook(){[Name="SalesClean"]}[Content],
Band = Table.AddColumn(
Source,
"SizeBand",
each if [Amount] = null then "Unknown"
else if [Amount] >= 10000 then "Large"
else if [Amount] >= 1000 then "Medium"
else "Small",
type text
)
in
BandArithmetic with null returns null. So [Quantity] * [UnitPrice] is null if either value is blank. Use the null-coalescing operator ?? to substitute a default, for example ([Discount] ?? 0).
Common errors
- Column not found: the formula uses
[amount]but the column isAmount. Field names are case-sensitive. - Cannot apply operator to types: you tried
[Quantity] & "x"on a number, or[Name] + 1on text. Convert withText.FromorNumber.From. - Wrong type on a mixed column: if a column holds errors or text in some rows, the formula fails for those rows only. The error appears in the new column cell. The next chapter covers
try ... otherwise. - Missing type: the new column stays
any, so the load to Excel may treat numbers or dates as general values. Always pass a type. - Step order: a custom column that refers to a column you later rename or remove will break. Add columns after cleaning, or edit the formula when you change names.
Comparing the two dialogs
| Feature | Custom Column | Conditional Column |
|---|---|---|
| Input | Any M expression | Pick column, operator, value |
| Best for | Math, text, dates, functions | Simple tiers and labels |
| Compare two columns | Yes | Yes, by choosing a column as the value |
| Editable later | Formula bar or gear icon | Gear icon, or formula bar |
You can start with the Conditional Column dialog, then open the formula bar to refine the generated code.
Query folding note
When the source is a database, a simple custom column may be translated into SQL and run on the server. Complex M functions can stop this translation. For an Excel table or CSV file, nothing folds, so this does not matter yet. A later chapter covers it.
Practice flow
- Import the table and set data types first.
- Clean text and fix nulls.
- Add the custom or conditional column, passing a type.
- Check a sample of rows, including blanks, against your rule.
- Confirm the step name is meaningful. Rename it, for example "Add SizeBand", so the Applied Steps list reads clearly.
Exercise
A query has a numeric Amount column. You write a conditional column with the tests [Amount] >= 1000 then "Medium", [Amount] >= 10000 then "Large", otherwise "Small". Amounts of 25000 come out as "Medium", and blank amounts come out as "Small". Explain both problems and give a corrected M expression.
Show answer
Tests run top to bottom and the first true one wins, so 25000 satisfies >= 1000 and never reaches the Large test. Blank amounts are null, and null >= 1000 is false, so they fall to the otherwise branch. Put the most restrictive test first and test for null explicitly: each if [Amount] = null then "Unknown" else if [Amount] >= 10000 then "Large" else if [Amount] >= 1000 then "Medium" else "Small", passing type text as the fourth argument of Table.AddColumn.
Exercise
You add each [Quantity] * [UnitPrice] with no type argument. What type does the new column have, and how do you fix it in M?
Show answer
It has type any. Pass type number as the fourth argument to Table.AddColumn, or add a Table.TransformColumnTypes step after it.