Sub topic 2
Power Query Editor and Applied Steps
This chapter assumes you can open Power BI Desktop, use Get Data to pick a source, and read a table of rows, columns, and data types. You do not need to know M, the Power Query formula language, but you will read a little of it here.
What the Power Query Editor does
When you connect to Excel, CSV, or SharePoint, Power BI does not load the raw data straight into your model. The data goes through Power Query first. The Power Query Editor is the window where you shape that data before it loads.
You open it in two ways:
- In the Get Data dialog, select Transform Data instead of Load.
- From the Home ribbon of Power BI Desktop, select Transform data. This reopens the editor for queries you already have.
A query is a saved recipe that starts at a source and ends at a table. Each query becomes one table in your model. The editor stores the recipe, not a copy of the result. Every refresh runs the recipe again against the current source.
The layout of the editor
The editor has five areas you will use constantly.
| Area | Location | What it does |
|---|---|---|
| Queries pane | Left | Lists every query, parameter, and function in the file |
| Data preview | Center | Shows the first rows of the current step's result |
| Ribbon | Top | Holds the transform commands (Home, Transform, Add Column, View) |
| Formula bar | Above the preview | Shows the M code for the selected step |
| Query Settings pane | Right | Shows the query name and the **Applied Steps** list |
If the formula bar or Query Settings pane is missing, turn it on from the View tab.
Applied steps
Applied steps are the ordered list of transformations in a query. Each time you promote a header, change a type, or remove a column, the editor adds one step. The steps run from top to bottom. Each step takes the output of the step above it as its input.
Selecting a step shows the data as it looked right after that step. This makes the list a history you can inspect. If a column disappears, click earlier steps until you find the one that removed it.
A typical Excel query starts like this:
- Source: opens the file.
- Navigation: picks a sheet or table from the file.
- Promoted Headers: turns the first row into column names.
- Changed Type: sets the data types.
What you can do to a step
Right-click a step, or use the icons beside it, to manage it.
- Rename it so the list explains your intent, for example
Removed test rowsinstead ofFiltered Rows. - Delete it. Deleting a step in the middle can break steps below it.
- Move it up or down, using the context menu. Order matters, and a move can cause errors.
- Insert Step After to add a step in the middle of the list.
- Delete Until End to remove a step and all the ones after it.
- Extract Previous to split the earlier steps into a new query.
A step with a gear icon has settings you can reopen. Selecting the gear shows the dialog you used when you created it. The Source and Navigation steps often have one, which is how you change a file path later.
Each step is M code
Every applied step is one line of M code. M is a functional language, and a query is a let ... in expression. Each step is a named value inside let, and the value after in is the query result.
The first example from this tutorial shows the pattern. It opens a local workbook, selects the Excel table named Sales, and sets two column types.
let
Source = Excel.Workbook(File.Contents("C:\Data\Sales.xlsx"), true, true),
SalesTable = Source{[Item = "Sales", Kind = "Table"]}[Data],
Typed = Table.TransformColumnTypes(SalesTable, {{"OrderDate", type date}, {"Amount", type number}})
in
TypedRead it from the top:
SourcecallsExcel.Workbookon the file. The twotruearguments mean "use the first row as headers" and "delay loading data types". The result is a table that lists the sheets, tables, and named ranges in the workbook.SalesTablepicks one row of that list by itsItemandKind, then takes theDatacolumn of that row, which holds the table itself.Typedis the last step. It is also the value afterin, so it is what the query returns.
Each name on the left of = is a step name. Each step refers to the one before it by name. That is how the "output feeds the next step" rule works in code. Steps with spaces in their names, such as Changed Type, appear in M as #"Changed Type".
The Advanced Editor
To see or edit the whole query as text, choose Home > Advanced Editor. Changes you make there appear in the applied steps list. Use it when you want to copy a query, fix a step the ribbon cannot reach, or review what the editor generated.
How steps run
Two properties of this model matter in practice.
Steps are lazy. M does not compute a step until something needs its value. The preview shows only the first rows, so the editor can feel fast on large files. The full run happens when you apply the changes or refresh.
Steps are replayed, not stored. The editor keeps no copy of your source data in the query. If the source file changes, the same steps run on the new content at the next refresh. This is why steps must describe rules, such as "remove column Notes", rather than one-time edits.
Writing steps that survive refresh
The most common refresh failure comes from steps that depend on something that later changes. Watch for these.
- Column names. A step like
Table.RemoveColumns(Typed, {"Notes"})fails with an error ifNotesis renamed or missing in the next file. If you only want the columns you need,Table.SelectColumnsstates the intent more safely, andTable.RemoveColumnsaccepts aMissingField.Ignoreargument that skips absent columns. - Column positions. Steps that use "first column" or column numbers break when the column order changes.
- Hard-coded row numbers. Removing "top 3 rows" works only while the file always has 3 junk rows.
- Automatic type detection. The editor may add a
Changed Typestep that guesses types from the first rows. A later row with different content, such as text in a number column, causes an error cell.
You can see the effect in a query that removes a column safely.
let
Source = Csv.Document(File.Contents("C:\Data\orders.csv"), [Delimiter = ",", Encoding = 65001, QuoteStyle = QuoteStyle.Csv]),
Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars = true]),
Typed = Table.TransformColumnTypes(Promoted, {{"OrderID", Int64.Type}, {"OrderDate", type date}}),
Cleaned = Table.RemoveColumns(Typed, {"Notes"}, MissingField.Ignore)
in
CleanedThis extends the CSV example from the plan with a fourth step. Without MissingField.Ignore, the Cleaned step would raise an error when Notes is absent.
Step order and its effects
Order changes the result. Two cases come up often.
- Filter before or after a type change. Filtering a date column with a date filter works only after the column has a date type. If you move the filter above the type step, the filter dialog offers text filters instead.
- Rename before later steps. If you rename
AmounttoTotaland then a later step namesAmount, that later step fails.
When you insert a step in the middle, the editor warns you that it may change later steps. Read that warning. After inserting, select the last step and check that the preview still has no errors.
Errors in the preview
An error can appear in two forms.
- A step error replaces the whole preview with a message such as
Expression.Error: The column 'Notes' of the table wasn't found.The step that raised it is the one selected, or the first one that shows a red message. Fix or remove that step. - A cell error shows
Errorin a single cell while the rest of the table loads. This usually comes from a type change on a value that does not fit. Use Home > Keep Rows > Keep Errors to list the bad rows, or Remove Errors if the rows are not needed.
A cell error does not stop the load, but it can silently drop data from a report if you remove errors without looking at them first.
Query settings that affect loading
Right-click a query in the Queries pane for options you will use often.
- Enable load controls whether the query becomes a table in the model. Turn it off for helper queries, such as a parameter or a file list, that only feed other queries.
- Include in report refresh controls whether the query refreshes with the report.
- Duplicate copies the query and all steps. Reference creates a new query that starts from the output of the original and does not repeat its steps.
Use Reference when two tables share the same source and cleaning, because the shared work lives in one place.
Closing and applying
When you finish, choose Close & Apply on the Home tab. Power BI runs each enabled query and loads the results into the model. Close without applying keeps your changes in the editor, but the model does not update. Pending changes show a yellow banner in the report window.
Practice
Exercise
A query has these applied steps in order: Source, Navigation, Promoted Headers, Changed Type, Removed Columns. A refresh fails with "The column 'Region' of the table wasn't found." The step Removed Columns removes "Region". Name one reason this can happen and one way to make the step safer.
Show answer
The new source file no longer has a column named Region, for example because it was renamed or dropped. The step cannot find it and raises a step error. To make the step safer, add MissingField.Ignore as the third argument to Table.RemoveColumns so it skips absent columns. Alternatively, use Table.SelectColumns to keep only the columns you need.
Exercise
You select the Changed Type step in the Applied Steps list and the preview shows the correct dates. You select Promoted Headers just above it and the date column shows text. What does this tell you about how applied steps work?
Show answer
Each applied step shows the data as it looked right after that step ran. Before Changed Type, the date column is still text, so selecting an earlier step shows the earlier state. Steps run top to bottom, and each step takes the output of the one above it.
Exercise
You have a query named Orders that connects to a CSV file and cleans it. You need a second table that summarizes Orders by month. Should you use Duplicate or Reference, and why?
Show answer
Use Reference. A referenced query starts from the output of Orders, so the connection and cleaning steps stay in one place and a fix to Orders flows to the summary. Duplicate copies all the steps, so you would have to change both queries when the source changes.