Sub topic 14
Reading the M code for append and merge
Every append and merge you build in the Power Query Editor is stored as M code, the language behind Power Query. You can build most queries without reading it. Reading it helps when you need to change a join kind in one place, apply the same fix to several queries, or work out why a refresh broke. This chapter shows what the editor generates for append and merge and how to edit it safely.
This chapter assumes you can build an append and a merge with the dialogs, and that you know what a join kind and a key column are. You don't need to have written M before.
Where to see the code
You can see the M code in two places.
- The formula bar shows the code for the selected applied step. If it is hidden, turn it on under View > Formula Bar.
- The Advanced Editor (Home > Advanced Editor) shows the whole query.
A query is one let ... in expression. Each line between let and in is one applied step. Each step has a name, and later steps refer to earlier ones by that name. The expression after in is the result the query returns.
let
Source = Table.Combine({Sales_2023, Sales_2024})
in
SourceHere Sales_2023 and Sales_2024 are the names of other queries in the workbook. In M you refer to a query by its name, just as you refer to a step. Names that contain spaces or special characters must be written as #"Sales 2023". The editor adds this form for you, which is why generated code often shows #"Changed Type" and #"Merged Queries".
Append: Table.Combine
Append Queries produces Table.Combine. It takes one argument, a list of tables written in braces, and returns all their rows stacked in list order.
When you start an append from an existing query, the first table in the list is the previous step, not a query name:
let
Source = Excel.CurrentWorkbook(){[Name="Sales_2023"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source, {{"CustomerID", type text}, {"Amount", type number}}),
#"Appended Query" = Table.Combine({#"Changed Type", Sales_2024})
in
#"Appended Query"Three behaviors of Table.Combine explain most append problems.
- Columns match by name, not by position. The result has every column that appears in any table. A column missing from one table is filled with
nullfor that table's rows. - Column order in the result follows the first appearance of each name, starting with the first table in the list.
- Types are not repaired. If
Amountis a number in one table and text in the other, the combined column has the typeany. Add aTable.TransformColumnTypesstep after the append if you need a single type.
If one table calls a column Cust ID and another calls it CustomerID, you get two columns that are each half empty. The fix is a rename in the table that is wrong, before the append. Table.RenameColumns(Source, {{"Cust ID", "CustomerID"}}) does this.
Merge: Table.NestedJoin
Merge Queries produces Table.NestedJoin. The arguments are, in order:
- The first (left) table.
- A list of key column names in the first table.
- The second (right) table.
- A list of key column names in the second table.
- The name of the new column that will hold the matching rows.
- The join kind.
let
Source = Table.NestedJoin(Orders, {"CustomerID"}, Customers, {"CustomerID"}, "Customers", JoinKind.LeftOuter)
in
SourceThe result is the left table plus one new column. Each cell in that column holds a whole table, containing the right-table rows that matched. A cell holds an empty table when nothing matched. This is why the merge dialog shows a column of Table links until you expand it.
The join kinds you pick in the dialog are constants in M:
| Dialog choice | M constant |
|---|---|
| Left Outer | `JoinKind.LeftOuter` |
| Right Outer | `JoinKind.RightOuter` |
| Full Outer | `JoinKind.FullOuter` |
| Inner | `JoinKind.Inner` |
| Left Anti | `JoinKind.LeftAnti` |
| Right Anti | `JoinKind.RightAnti` |
Changing a join kind is a one-word edit in the formula bar. You can edit the code this way without reopening the dialog.
Multiple key columns
Key arguments are always lists, even for one column. For several keys, put the names in both lists. The columns are paired by position: the first name in the left list matches the first name in the right list, and so on.
let
Source = Table.NestedJoin(Prices, {"Region", "Product"}, Targets, {"Region", "Product"}, "Targets", JoinKind.Inner)
in
SourceThe two lists must have the same length. If you reorder one list and not the other, you pair the wrong columns, and the join may return no rows without raising an error.
Expanding and aggregating the nested column
After a merge, the dialog's expand button generates Table.ExpandTableColumn. Its arguments are the table, the nested column name, the columns to take, and optionally the new names for those columns.
let
Merged = Table.NestedJoin(Orders, {"CustomerID"}, Customers, {"CustomerID"}, "Customers", JoinKind.LeftOuter),
Expanded = Table.ExpandTableColumn(Merged, "Customers", {"Name", "Region"}, {"Customer Name", "Customer Region"})
in
ExpandedIf you leave "Use original column name as prefix" ticked, the generated list of new names is {"Customers.Name", "Customers.Region"}. The fourth argument is how you rename the columns during the expand.
Expanding adds one output row for each matching right-table row. If a customer has three orders, expanding Orders from the Customers side gives three rows for that customer. To keep one row per customer, aggregate instead. Table.AggregateTableColumn takes a list of triples: source column, aggregating function, new column name.
let
Source = Table.NestedJoin(Customers, {"CustomerID"}, Orders, {"CustomerID"}, "Orders", JoinKind.LeftOuter),
Totals = Table.AggregateTableColumn(Source, "Orders", {{"Amount", List.Sum, "Total Amount"}})
in
TotalsList.Sum is passed without parentheses. You are handing M the function itself, and it calls the function on each nested table's column. Other functions that work the same way include List.Count, List.Max, List.Min, and List.Average.
Fuzzy merges
A fuzzy merge uses Table.FuzzyNestedJoin, which has the same first six arguments as Table.NestedJoin and then an options record in square brackets.
let
Source = Table.FuzzyNestedJoin(Orders, {"CustomerName"}, Customers, {"CustomerName"}, "Matches", JoinKind.LeftOuter, [IgnoreCase = true, IgnoreSpace = true, Threshold = 0.8])
in
SourceThreshold is a similarity between 0 and 1. Higher values accept fewer matches. If you lower it to catch more typos, check the matched rows, because it will also pair values that should stay separate.
How the steps connect
The diagram shows a typical generated pipeline. Each box is one step, and each arrow means the next step takes the previous step's result as its first argument.
Here is the same pipeline as one query:
let
Appended = Table.Combine({Sales_2023, Sales_2024}),
Typed = Table.TransformColumnTypes(Appended, {{"CustomerID", type text}, {"Amount", type number}}),
Merged = Table.NestedJoin(Typed, {"CustomerID"}, Customers, {"CustomerID"}, "Customers", JoinKind.LeftOuter),
Expanded = Table.ExpandTableColumn(Merged, "Customers", {"Name", "Region"}, {"Name", "Region"})
in
ExpandedThe step names Appended, Typed, Merged, and Expanded are plain identifiers, so they need no #"..." form. Renaming steps in the Applied Steps pane updates later references for you. If you rename in the Advanced Editor, update every later reference yourself.
Editing the code safely
Some edits are worth making by hand:
- Change the join kind by replacing the constant.
- Add a query to an append by adding its name to the list in
Table.Combine. - Rename the columns that come from an expand through the fourth argument.
- Insert a cleaning step before a merge, such as the
Text.Upper(Text.Trim(_))transformation, and point the merge at the new step name.
Some things break in ways the code does not make obvious:
- Hard-coded column lists.
Table.ExpandTableColumnnames the columns it takes. If the right table later gains a column, it will not appear until you edit the list. If a named column is removed or renamed, the refresh fails with an error that the column was not found. - Case sensitivity. M is case sensitive.
joinkind.leftouterandTable.nestedjoinproduce errors, and so does"CustomerId"when the column isCustomerID. - Commas. A missing comma between steps, or a comma after the last step before
in, is the most common syntax error. The Advanced Editor shows a message when it finds one. - Missing results. If you remove a step that later steps depend on, those steps show an error. Check that
instill names the step you want returned.
Checking row counts in M
You can check a merge in code as well as in the preview. Add a step that returns a record instead of a table, test it, and then change in back.
let
Typed = Table.TransformColumnTypes(Table.Combine({Sales_2023, Sales_2024}), {{"CustomerID", type text}}),
Merged = Table.NestedJoin(Typed, {"CustomerID"}, Customers, {"CustomerID"}, "Customers", JoinKind.LeftOuter),
Expanded = Table.ExpandTableColumn(Merged, "Customers", {"Name"}, {"Name"}),
Check = [RowsBefore = Table.RowCount(Typed), RowsAfter = Table.RowCount(Expanded), Unmatched = Table.RowCount(Table.SelectRows(Expanded, each [Name] = null))]
in
CheckWith a left outer join, RowsAfter should equal RowsBefore unless the right table has duplicate keys. A nonzero Unmatched tells you how many rows found no match, though it also counts rows where a matched customer has a blank name.
Exercise
A query ends with Table.NestedJoin(Orders, {"Region", "Product"}, Targets, {"Product", "Region"}, "Targets", JoinKind.Inner). The key columns exist in both tables, yet the result has no rows. What is wrong, and how do you fix it?
Show answer
The key lists are paired by position, so Region in Orders is compared with Product in Targets, and Product with Region. Values in those columns rarely match, so the inner join returns nothing. Make the second list {"Region", "Product"} so both lists use the same order.
Exercise
You append Sales_2023 and Sales_2024. In the result, the Amount column has the type any, and a column called Cust ID is mostly null while CustomerID is also mostly null. Name one fix for each problem in M terms.
Show answer
For the type, add a Table.TransformColumnTypes step after Table.Combine that sets Amount to type number. For the split column, rename the mismatched column in the table that uses Cust ID with Table.RenameColumns before the Table.Combine step, so both tables use CustomerID.