Sub topic 2
Applied Steps and the M code behind them
Every change you make in the Power Query Editor is recorded as a step. Each step is a line of code in a language called M. This chapter explains how the Applied Steps pane maps to M, how to read the code, and how to make small, safe edits.
This chapter assumes you can open Power BI Desktop, connect to a CSV or Excel file, and open the Power Query Editor. You should also know what tables, rows, columns, and data types are.
What Applied Steps are
The Applied Steps pane sits in the Query Settings panel on the right side of the editor. It lists every transformation in a query, in the order Power Query runs them. When you load a CSV, promote headers, and change a type, you get steps such as Source, Promoted Headers, and Changed Type.
Three properties of steps matter in practice:
- Each step takes the previous step's output as input. A step does not change the source file. It describes a new table derived from the one before it.
- Order matters. Removing a column before filtering on it breaks the filter. Replacing values before changing a type can give a different result than doing it after.
- Clicking a step shows the data as it looked at that point. This makes steps a debugging tool. If a value is wrong in the final table, click earlier steps until the value is right, and the step after that one is the cause.
You can rename a step (right-click, Rename, or press F2), delete it with the X icon, reorder it by dragging, or insert a new step after any step by selecting that step and then applying a transformation.
The M language and the formula bar
M is the language behind Power Query. It is a functional language. A query is a series of named values, each defined from earlier ones. The editor writes this code for you, but it is ordinary text you can read and edit.
The formula bar shows the M expression for the selected step. If you don't see it, turn it on under the View tab by checking Formula Bar. Select the Changed Type step and you might see:
= Table.TransformColumnTypes(PromotedHeaders, {{"OrderID", Int64.Type}, {"OrderDate", type date}, {"Amount", type number}}, "en-US")This reads as: call the function Table.TransformColumnTypes. Its first argument is the table from the step named PromotedHeaders. The second is a list of column and type pairs. The third is the culture, here en-US.
Reading a full query in the Advanced Editor
To see all steps at once, choose Home, then Advanced Editor. The code below loads a CSV file, promotes the first row to headers, and sets types.
let
Source = Csv.Document(File.Contents("C:\Data\sales.csv"), [Delimiter = ",", Encoding = 65001]),
PromotedHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars = true]),
ChangedType = Table.TransformColumnTypes(PromotedHeaders, {{"OrderID", Int64.Type}, {"OrderDate", type date}, {"Amount", type number}}, "en-US")
in
ChangedTypeA query has this structure:
letopens the list of steps.- Each line has the form
StepName = expression, and lines are separated by commas. The last step has no trailing comma. innames the step whose value the query returns. Here it isChangedType, the last step.
Each step name is a variable. PromotedHeaders is the output of Table.PromoteHeaders and becomes the input of the next line. This is why the Applied Steps pane shows a chain: the chain is a sequence of variable references.
The code uses Csv.Document, with Encoding = 65001 meaning UTF-8. You can see how a choice you made in the connection dialog turns into arguments in the code.
How pane names map to M names
The pane shows friendly names, but M uses identifiers. The editor converts between them.
| Pane name | M identifier |
|---|---|
| Source | `Source` |
| Promoted Headers | `PromotedHeaders` |
| Changed Type | `ChangedType` |
| Filtered Rows | `FilteredRows` |
| Removed Duplicates | `RemovedDuplicates` |
When a name contains spaces or special characters, M writes it as #"Name with spaces". For example, if you rename a step to Clean amounts, later steps refer to it as #"Clean amounts". This is called a quoted identifier. The same syntax applies to column names in some contexts. Renaming steps in the pane updates every reference for you. Renaming it in the Advanced Editor does not, so you must edit each reference yourself.
A diagram of the data flow
The diagram shows how each step feeds the next and how the pane relates to the code.
A second example: reading a longer query
The following query builds a small table in code, so you can paste it into a blank query and run it without any file. It cleans text, fills missing values, removes duplicates, and handles an error.
let
Source = #table(
{"Customer", "Region", "Amount"},
{
{" alice smith ", "West", "120"},
{"BOB JONES", null, "abc"},
{"BOB JONES", null, "abc"}
}
),
CleanedText = Table.TransformColumns(Source, {{"Customer", each Text.Proper(Text.Trim(Text.Clean(_))), type text}}),
FilledRegion = Table.ReplaceValue(CleanedText, null, "Unknown", Replacer.ReplaceValue, {"Region"}),
RemovedDuplicates = Table.Distinct(FilledRegion),
ChangedType = Table.TransformColumnTypes(RemovedDuplicates, {{"Amount", type number}}, "en-US"),
ReplacedErrors = Table.ReplaceErrorValues(ChangedType, {{"Amount", 0}})
in
ReplacedErrorsRead it from top to bottom and match each line to a pane step:
Sourcecreates the table with#table. It takes a list of column names and a list of rows.CleanedTextuseseach, which defines a small function applied to every value in the column. The underscore_stands for the current value.FilledRegionreplacesnullwith"Unknown"in theRegioncolumn only.RemovedDuplicateskeeps one copy of rows that are identical across all columns.ChangedTypeconvertsAmountto numbers. The text"abc"cannot convert, so the cell becomes an error.ReplacedErrorsreplaces that error with0.
Later chapters cover each of these transformations. Here the goal is to see that one pane step is one line of M.
Making small edits safely
You do not need to write M from scratch. You do need to edit it sometimes. These edits are low risk and common:
- Change a literal. Edit a file path in the
Sourcestep, or change"Unknown"to"N/A". - Change a threshold. In a conditional column, change
>= 1000to>= 5000. - Rename a step. Do this in the pane so references update.
- Add a column to a list. In
Table.TransformColumnTypes, add another{"ColumnName", type text}pair.
Use the formula bar for one step and the Advanced Editor for several. After any edit, check the preview. If a step shows an error, the message names the problem.
Two rules apply to all M code:
- M is case-sensitive.
Table.Distinctworks.table.distinctdoes not. Column names also must match exactly, including capitalization and spaces. - Every reference must exist earlier in the query. A step can only use names defined above it, so moving a step in the pane can break later steps.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Expression.Error: The name 'X' wasn't recognized` | A misspelled step or function name, wrong case, or a deleted step still referenced | Correct the name, or point the reference at an existing step |
| `Expression.Error: The column 'X' of the table wasn't found` | The source column was renamed or removed, or an earlier step changed it | Update the column name, or check for an earlier rename step |
| `Token Comma expected` | A missing comma at the end of a step line | Add the comma. The last step before `in` has none |
| `Token Eof expected` | An extra comma after the last step, or text after the final expression | Remove the extra comma or text |
| A warning "Delete step? Later steps may be affected" | Later steps depend on the one you are deleting | Review them first, since deleting may break the query |
When you insert a step in the middle of the chain, the editor may warn that "Insert Step" will change later steps. Accept this only if the new step does not rename or remove columns that later steps use.
Steps you cannot see in the pane
Some steps show a small gear icon. Clicking it reopens the dialog for that step, such as the delimiter choices on a split. Steps without a gear were produced by a simple action, and you edit them through the formula bar instead.
A step that appears in the Advanced Editor but does not appear in the pane can happen when you write code by hand that uses a helper variable. The pane shows every variable in the let block, so each assignment appears as a step.
Be careful with the Advanced Editor when the editor has generated steps. A change in the pane after a manual edit may rewrite part of the code, so check the result after each edit.
Summary of the working model
A query is a chain of steps. Each step is one named line of M. The pane lists the lines, the formula bar shows one line, and the Advanced Editor shows all of them. The in clause decides which step becomes the query's output. If you can read a line as "name equals function applied to previous step plus options," you can read most generated M.
Exercise
In the following query, which step does the query return, and what breaks if you move the Filtered step above Typed?
let
Source = #table({"Qty"}, {{"5"}, {"15"}}),
Typed = Table.TransformColumnTypes(Source, {{"Qty", Int64.Type}}, "en-US"),
Filtered = Table.SelectRows(Typed, each [Qty] > 10)
in
Filtered
Show answer
The query returns Filtered, because it follows in. If you move Filtered above Typed, it would take Source or an undefined name as input depending on how you rewrite it. In the pane, it would filter text values before they are converted, so comparing text "5" with the number 10 raises an error. Keep the type change before any numeric comparison.
Exercise
You rename the step Changed Type to Typed Columns in the Advanced Editor, and now the query shows "The name 'ChangedType' wasn't recognized". Why, and how do you fix it?
Show answer
The next step still refers to the old name ChangedType. Renaming in the Advanced Editor does not update references. Change the reference in the following step to #"Typed Columns", or rename the step in the Applied Steps pane next time so references update automatically.