Sub topic 7
Merging two queries on a key column
This chapter assumes you can load tables into the Power Query Editor, that you know the basic data types (text, number, date), and that you have used a lookup or join before. It also assumes you know the difference between stacking rows (append) and adding columns (merge), which an earlier chapter covered.
What a merge does
A merge adds columns to one table by matching its rows against rows in a second table. The matching is done on a key column, a column whose values identify the same thing in both tables. In this chapter the key is CustomerID, which appears in both Orders and Customers.
A merge is Power Query's version of a join in a database, or a more flexible form of XLOOKUP. Unlike a lookup formula, one merge can bring over many columns at once, and the result refreshes with the rest of the query.
Every merge has two inputs:
- The first table is the one you keep. Its row order is preserved in the result.
- The second table is the one you look things up in.
The merge produces a new column in the first table. Each cell in that column holds a small table, made of the matching rows from the second table. You then expand that column to turn it into ordinary columns.
Sample data
To follow along, create two blank queries in Excel (Data > Get Data > From Other Sources > Blank Query), open each in the Advanced Editor, and paste these definitions. Name them Orders and Customers.
let
Source = #table(
type table [OrderID = Int64.Type, CustomerID = text, Amount = number],
{
{1001, "C01", 250},
{1002, "C02", 90},
{1003, "C09", 40},
{1004, "C01", 120}
}
)
in
Sourcelet
Source = #table(
type table [CustomerID = text, Name = text, Region = text],
{
{"C01", "Ava Chen", "East"},
{"C02", "Ben Ortiz", "West"},
{"C03", "Cara Singh", "East"}
}
)
in
SourceTwo details are deliberate. Order 1003 belongs to customer C09, who is not in Customers. Customer C03 has no orders. You will see how each case behaves.
Running the merge in the editor
- In the Power Query Editor, select the
Ordersquery in the Queries pane. - On the Home tab, choose Merge Queries. The alternative, Merge Queries as New, leaves
Ordersuntouched and creates a third query for the result. Use it when you want to keep the original table available. - In the Merge dialog, the top preview is the first table. Click the
CustomerIDheader to select it. - In the dropdown below, choose
Customers, then click itsCustomerIDheader. - Leave Join Kind as Left Outer (all from first, matching from second).
- Check the message at the bottom. For this data it reads "The selection matches 3 of 4 rows from the first table." Click OK.
A new column named Customers appears at the right of Orders. Each cell says Table. Click a cell's whitespace (not the word) to preview its contents in the pane below the grid.
Merging on more than one column
Sometimes one column does not identify a row, for example when a product is only unique within a region. In the dialog, hold Ctrl and click several headers in the first table, then do the same in the second table. Small numbers (1, 2) appear in the headers to show the pairing.
The order of your clicks matters. The first column selected in the top table is paired with the first column selected in the bottom table, and so on. If you click Region then Product on one side and Product then Region on the other, the pairs will be wrong and nothing will match.
Expanding the result
Click the expand icon (two arrows) in the Customers column header. A checklist of the second table's columns appears.
- Clear the key column
CustomerID, since you already have it. - Keep
NameandRegionselected. - Clear "Use original column name as prefix" if you want plain names such as
Nameinstead ofCustomers.Name.
Click OK. The result looks like this:
| OrderID | CustomerID | Amount | Name | Region |
|---|---|---|---|---|
| 1001 | C01 | 250 | Ava Chen | East |
| 1002 | C02 | 90 | Ben Ortiz | West |
| 1003 | C09 | 40 | null | null |
| 1004 | C01 | 120 | Ava Chen | East |
Order 1003 stays in the result with null in the new columns, because a left outer merge keeps every row of the first table. Customer C03 does not appear at all, because she has no match in the first table. The next chapter covers the other join kinds and which rows each one keeps.
The M code behind it
The dialog writes two steps. This is the same merge, with the expand, as it appears in the Advanced Editor:
let
Source = Table.NestedJoin(Orders, {"CustomerID"}, Customers, {"CustomerID"}, "Customers", JoinKind.LeftOuter),
Expanded = Table.ExpandTableColumn(Source, "Customers", {"Name", "Region"}, {"Name", "Region"})
in
ExpandedTable.NestedJoin takes six arguments, in this order:
- The first table.
- A list of key column names in the first table.
- The second table.
- A list of key column names in the second table.
- The name of the new column that will hold the nested tables.
- The join kind.
The key names are always lists, even for one column. For several keys you write {"Region", "Product"} on both sides, in matching order.
Table.ExpandTableColumn takes the table, the nested column's name, the list of columns to pull out, and a list of names to give them. Changing the last list renames the new columns, which is a clean way to avoid name clashes.
Rules the match follows
The dialog's matching is strict, and most merge problems trace back to one of these rules.
- Matching is exact.
"C01"and"c01"do not match, and neither do"C01"and"C01 "(with a trailing space). - Types must agree. The text
"1"and the number1do not match. Set both key columns to the same type before merging. - Nulls do not match anything useful. Rows with a null key are treated as having no partner.
- The first table is the reference. Swapping the two tables changes which rows survive, even when the join kind stays the same.
- If the second table has several rows with the same key, each match becomes a row in the nested table. When you expand, the first table's row repeats once per match.
Merge or Merge as New
| Choice | Result | Use it when |
|---|---|---|
| Merge Queries | Adds a merge step to the selected query | The merged table is the only version you need |
| Merge Queries as New | Creates a new query and leaves both sources unchanged | You still need the originals, or several queries build on the same source |
If the source queries are set to Connection only, as covered in the loading chapter, neither choice loads the unmerged tables into the workbook. Only the final merged query needs a worksheet or Data Model destination.
When the two inputs come from different sources, Excel may show a privacy levels prompt. It asks how far data may be shared between sources. Choose levels that match your policy rather than ignoring the prompt, because it affects whether the merge can fold into a single source query.
Exercise
In the sample data, you merge Orders (first table) with Customers (second table) on CustomerID using Left Outer, then expand Name. How many rows does the result have, and what does the Name column show for OrderID 1003?
Show answer
The result has 4 rows, the same as Orders, because a left outer merge keeps every row of the first table. Order 1003 belongs to C09, who is not in Customers, so Name is null for that row.
Exercise
You merge Prices and Targets on Region and Product. In the dialog you click Region then Product in Prices, but Product then Region in Targets. The dialog reports 0 matches. Why, and how do you fix it?
Show answer
Power Query pairs the selected columns by click order, so Region in Prices is paired with Product in Targets, and Product with Region. Select the columns in the same order in both tables, Region then Product (or Product then Region) on each side, and the numbered markers in the headers will line up.
Exercise
The Customers table contains two rows for CustomerID C01. What happens to Orders rows 1001 and 1004 when you expand Name and Region, and where can you catch it?
Show answer
Each of those orders matches two Customers rows, so each order appears twice after expanding, giving 6 rows instead of 4. Comparing the row count before and after the merge catches it. Removing the duplicate key from Customers, or aggregating the nested table instead of expanding it, fixes it.